Merge commit '4536c5cf2d7b8e68768f90d281b3e4974cd26ae9'
[nikiroo-utils.git] / 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 be.nikiroo.utils.Image;
14 import be.nikiroo.utils.ImageUtils;
15 import be.nikiroo.utils.StringUtils;
16
17 /**
18 * This class offer some utilities based around images and uses the Android
19 * framework.
20 *
21 * @author niki
22 */
23 public class ImageUtilsAndroid extends ImageUtils {
24 @Override
25 protected boolean check() {
26 // If we can get the class, it means we have access to it
27 Config c = Config.ALPHA_8;
28 return true;
29 }
30
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 chance: 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 {
75 InputStream stream = img.newInputStream();
76 try {
77 Bitmap image = BitmapFactory.decodeStream(stream);
78 if (image == null) {
79 String extra = "";
80 if (img.getSize() <= 2048) {
81 try {
82 extra = ", content: "
83 + new String(img.getData(), "UTF-8");
84 } catch (Exception e) {
85 extra = ", content unavailable";
86 }
87 }
88 String ssize = StringUtils.formatNumber(img.getSize());
89 throw new IOException(
90 "Failed to convert input to image, size was: " + ssize
91 + extra);
92 }
93
94 return image;
95 } finally {
96 stream.close();
97 }
98 }
99 }