Version 4.6.2
[nikiroo-utils.git] / src / be / nikiroo / utils / android / ImageUtilsAndroid.java
CommitLineData
e8aa5bf9
NR
1package be.nikiroo.utils.android;
2
3import android.graphics.Bitmap;
4import android.graphics.BitmapFactory;
e8aa5bf9
NR
5
6import java.io.File;
7import java.io.FileOutputStream;
8import java.io.IOException;
9
e704a414
NR
10import be.nikiroo.utils.Image;
11import be.nikiroo.utils.ImageUtils;
12
e8aa5bf9 13/**
e704a414
NR
14 * This class offer some utilities based around images and uses the Android
15 * framework.
e8aa5bf9
NR
16 *
17 * @author niki
18 */
19public class ImageUtilsAndroid extends ImageUtils {
20 @Override
21 public void saveAsImage(Image img, File target, String format)
22 throws IOException {
23 FileOutputStream fos = new FileOutputStream(target);
24 try {
25 Bitmap image = fromImage(img);
26
27 boolean ok = false;
28 try {
29 ok = image.compress(
30 Bitmap.CompressFormat.valueOf(format.toUpperCase()),
31 90, fos);
32 } catch (Exception e) {
33 ok = false;
34 }
35
36 // Some formats are not reliable
37 // Second change: PNG
38 if (!ok && !format.equals("png")) {
39 ok = image.compress(Bitmap.CompressFormat.PNG, 90, fos);
40 }
41
42 if (!ok) {
43 throw new IOException(
44 "Cannot find a writer for this image and format: "
45 + format);
46 }
47 } catch (IOException e) {
48 throw new IOException("Cannot write image to " + target, e);
49 } finally {
50 fos.close();
51 }
52 }
53
54 /**
55 * Convert the given {@link Image} into a {@link Bitmap} object.
56 *
57 * @param img
58 * the {@link Image}
59 * @return the {@link Image} object
60 * @throws IOException
61 * in case of IO error
62 */
63 static public Bitmap fromImage(Image img) throws IOException {
64 Bitmap image = BitmapFactory.decodeByteArray(img.getData(), 0,
65 img.getData().length);
66 if (image == null) {
e704a414
NR
67 int size = img.getData().length;
68 String ssize = size + " byte";
69 if (size > 1) {
70 ssize = size + " bytes";
71 if (size >= 1000) {
72 size = size / 1000;
73 ssize = size + " kb";
74 if (size > 1000) {
75 size = size / 1000;
76 ssize = size + " MB";
77 }
78 }
79 }
80
81 throw new IOException(
82 "Failed to convert input to image, size was: " + ssize);
e8aa5bf9
NR
83 }
84
85 return image;
86 }
87}