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