Merge branch 'subtree'
[fanfix.git] / src / be / nikiroo / utils / android / ImageUtilsAndroid.java
CommitLineData
e8aa5bf9
NR
1package be.nikiroo.utils.android;
2
3import android.graphics.Bitmap;
a2c1d5fe 4import android.graphics.Bitmap.Config;
e8aa5bf9 5import android.graphics.BitmapFactory;
e8aa5bf9
NR
6
7import java.io.File;
8import java.io.FileOutputStream;
9import java.io.IOException;
a2c1d5fe
NR
10import java.io.InputStream;
11import java.util.stream.Stream;
e8aa5bf9 12
e704a414
NR
13import be.nikiroo.utils.Image;
14import be.nikiroo.utils.ImageUtils;
67bcea89 15import be.nikiroo.utils.StringUtils;
e704a414 16
e8aa5bf9 17/**
e704a414
NR
18 * This class offer some utilities based around images and uses the Android
19 * framework.
e8aa5bf9
NR
20 *
21 * @author niki
22 */
23public class ImageUtilsAndroid extends ImageUtils {
10b6023d
NR
24 @Override
25 protected boolean check() {
26 // If we can get the class, it means we have access to it
d01bd74e 27 Config c = Config.ALPHA_8;
10b6023d
NR
28 return true;
29 }
a2c1d5fe 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
22f24988 48 // Second chance: PNG
e8aa5bf9
NR
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 {
a2c1d5fe
NR
75 InputStream stream = img.newInputStream();
76 try {
77 Bitmap image = BitmapFactory.decodeStream(stream);
78 if (image == null) {
c48600a5 79 String extra = "";
59654e2a 80 if (img.getSize() <= 2048) {
c48600a5
NR
81 try {
82 extra = ", content: "
83 + new String(img.getData(), "UTF-8");
84 } catch (Exception e) {
85 extra = ", content unavailable";
86 }
87 }
a2c1d5fe
NR
88 String ssize = StringUtils.formatNumber(img.getSize());
89 throw new IOException(
c48600a5
NR
90 "Failed to convert input to image, size was: " + ssize
91 + extra);
a2c1d5fe 92 }
d01bd74e
NR
93
94 return image;
a2c1d5fe
NR
95 } finally {
96 stream.close();
e8aa5bf9 97 }
e8aa5bf9
NR
98 }
99}