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