add checks on ImageUtils instances
[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
10b6023d
NR
10import javax.imageio.ImageIO;
11
e704a414
NR
12import be.nikiroo.utils.Image;
13import be.nikiroo.utils.ImageUtils;
67bcea89 14import be.nikiroo.utils.StringUtils;
e704a414 15
e8aa5bf9 16/**
e704a414
NR
17 * This class offer some utilities based around images and uses the Android
18 * framework.
e8aa5bf9
NR
19 *
20 * @author niki
21 */
22public class ImageUtilsAndroid extends ImageUtils {
10b6023d
NR
23 @Override
24 protected boolean check() {
25 // If we can get the class, it means we have access to it
26 @SuppressWarnings("unused")
27 Object test = Bitmap.class;
28 return true;
29 }
30
e8aa5bf9
NR
31 @Override
32 public void saveAsImage(Image img, File target, String format)
33 throws IOException {
34 FileOutputStream fos = new FileOutputStream(target);
35 try {
36 Bitmap image = fromImage(img);
37
38 boolean ok = false;
39 try {
40 ok = image.compress(
41 Bitmap.CompressFormat.valueOf(format.toUpperCase()),
42 90, fos);
43 } catch (Exception e) {
44 ok = false;
45 }
46
47 // Some formats are not reliable
48 // Second change: PNG
49 if (!ok && !format.equals("png")) {
50 ok = image.compress(Bitmap.CompressFormat.PNG, 90, fos);
51 }
52
53 if (!ok) {
54 throw new IOException(
55 "Cannot find a writer for this image and format: "
56 + format);
57 }
58 } catch (IOException e) {
59 throw new IOException("Cannot write image to " + target, e);
60 } finally {
61 fos.close();
62 }
63 }
64
65 /**
66 * Convert the given {@link Image} into a {@link Bitmap} object.
67 *
68 * @param img
69 * the {@link Image}
70 * @return the {@link Image} object
71 * @throws IOException
72 * in case of IO error
73 */
74 static public Bitmap fromImage(Image img) throws IOException {
7b42695f
NR
75 byte[] array = img.getData();
76 int size = array.length;
10b6023d 77 // TODO: check if we can use a stream, too
7b42695f 78 Bitmap image = BitmapFactory.decodeByteArray(array, 0, size);
e8aa5bf9 79 if (image == null) {
67bcea89 80 String ssize = StringUtils.formatNumber(size);
e704a414
NR
81 throw new IOException(
82 "Failed to convert input to image, size was: " + ssize);
e8aa5bf9
NR
83 }
84
85 return image;
86 }
87}