| 1 | package be.nikiroo.utils.android; |
| 2 | |
| 3 | import android.graphics.Bitmap; |
| 4 | import android.graphics.BitmapFactory; |
| 5 | |
| 6 | import java.io.File; |
| 7 | import java.io.FileOutputStream; |
| 8 | import java.io.IOException; |
| 9 | |
| 10 | import be.nikiroo.utils.Image; |
| 11 | import be.nikiroo.utils.ImageUtils; |
| 12 | import be.nikiroo.utils.StringUtils; |
| 13 | |
| 14 | /** |
| 15 | * This class offer some utilities based around images and uses the Android |
| 16 | * framework. |
| 17 | * |
| 18 | * @author niki |
| 19 | */ |
| 20 | public 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 { |
| 65 | byte[] array = img.getData(); |
| 66 | int size = array.length; |
| 67 | Bitmap image = BitmapFactory.decodeByteArray(array, 0, size); |
| 68 | if (image == null) { |
| 69 | String ssize = StringUtils.formatNumber(size); |
| 70 | throw new IOException( |
| 71 | "Failed to convert input to image, size was: " + ssize); |
| 72 | } |
| 73 | |
| 74 | return image; |
| 75 | } |
| 76 | } |