Version 4.0.1: android compatibility
[nikiroo-utils.git] / src / be / nikiroo / utils / android / ImageUtilsAndroid.java
1 package be.nikiroo.utils.android;
2
3 import android.graphics.Bitmap;
4 import android.graphics.BitmapFactory;
5 import be.nikiroo.utils.Image;
6 import be.nikiroo.utils.ImageUtils;
7
8 import java.io.File;
9 import java.io.FileOutputStream;
10 import java.io.IOException;
11
12 /**
13 * This class offer some utilities based around images and uses the Android framework.
14 *
15 * @author niki
16 */
17 public class ImageUtilsAndroid extends ImageUtils {
18 @Override
19 public void saveAsImage(Image img, File target, String format)
20 throws IOException {
21 FileOutputStream fos = new FileOutputStream(target);
22 try {
23 Bitmap image = fromImage(img);
24
25 boolean ok = false;
26 try {
27 ok = image.compress(
28 Bitmap.CompressFormat.valueOf(format.toUpperCase()),
29 90, fos);
30 } catch (Exception e) {
31 ok = false;
32 }
33
34 // Some formats are not reliable
35 // Second change: PNG
36 if (!ok && !format.equals("png")) {
37 ok = image.compress(Bitmap.CompressFormat.PNG, 90, fos);
38 }
39
40 if (!ok) {
41 throw new IOException(
42 "Cannot find a writer for this image and format: "
43 + format);
44 }
45 } catch (IOException e) {
46 throw new IOException("Cannot write image to " + target, e);
47 } finally {
48 fos.close();
49 }
50 }
51
52 /**
53 * Convert the given {@link Image} into a {@link Bitmap} object.
54 *
55 * @param img
56 * the {@link Image}
57 * @return the {@link Image} object
58 * @throws IOException
59 * in case of IO error
60 */
61 static public Bitmap fromImage(Image img) throws IOException {
62 Bitmap image = BitmapFactory.decodeByteArray(img.getData(), 0,
63 img.getData().length);
64 if (image == null) {
65 throw new IOException("Failed to convert input to image");
66 }
67
68 return image;
69 }
70 }