1 package org.robolectric.shadows; 2 3 import android.graphics.Bitmap; 4 import android.graphics.Bitmap.CompressFormat; 5 import android.graphics.Point; 6 import java.awt.image.BufferedImage; 7 import java.io.IOException; 8 import java.io.InputStream; 9 import java.io.OutputStream; 10 import java.util.Iterator; 11 import java.util.Locale; 12 import javax.imageio.IIOImage; 13 import javax.imageio.ImageIO; 14 import javax.imageio.ImageReader; 15 import javax.imageio.ImageWriteParam; 16 import javax.imageio.ImageWriter; 17 import javax.imageio.plugins.jpeg.JPEGImageWriteParam; 18 import javax.imageio.stream.ImageInputStream; 19 import javax.imageio.stream.ImageOutputStream; 20 21 public class ImageUtil { 22 private static boolean initialized; 23 getImageSizeFromStream(InputStream is)24 public static Point getImageSizeFromStream(InputStream is) { 25 if (!initialized) { 26 // Stops ImageIO from creating temp files when reading images 27 // from input stream. 28 ImageIO.setUseCache(false); 29 initialized = true; 30 } 31 32 try { 33 ImageInputStream imageStream = ImageIO.createImageInputStream(is); 34 Iterator<ImageReader> readers = ImageIO.getImageReaders(imageStream); 35 if (!readers.hasNext()) return null; 36 37 ImageReader reader = readers.next(); 38 try { 39 reader.setInput(imageStream); 40 return new Point(reader.getWidth(0), reader.getHeight(0)); 41 } finally { 42 reader.dispose(); 43 } 44 } catch (IOException e) { 45 throw new RuntimeException(e); 46 } 47 } 48 writeToStream( Bitmap realBitmap, CompressFormat format, int quality, OutputStream stream)49 public static boolean writeToStream( 50 Bitmap realBitmap, CompressFormat format, int quality, OutputStream stream) { 51 if ((quality < 0) || (quality > 100)) { 52 throw new IllegalArgumentException("Quality out of bounds!"); 53 } 54 55 try { 56 ImageWriter writer = null; 57 Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName(getFormatName(format)); 58 if (iter.hasNext()) { 59 writer = (ImageWriter) iter.next(); 60 } 61 try (ImageOutputStream ios = ImageIO.createImageOutputStream(stream)) { 62 writer.setOutput(ios); 63 ImageWriteParam iwparam = new JPEGImageWriteParam(Locale.getDefault()); 64 iwparam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); 65 iwparam.setCompressionQuality((quality / 100f)); 66 writer.write( 67 null, 68 new IIOImage( 69 new BufferedImage( 70 realBitmap.getWidth(), realBitmap.getHeight(), BufferedImage.TYPE_BYTE_BINARY), 71 null, 72 null), 73 iwparam); 74 ios.flush(); 75 writer.dispose(); 76 } 77 78 } catch (IOException e) { 79 return false; 80 } 81 82 return true; 83 } 84 getFormatName(CompressFormat compressFormat)85 private static String getFormatName(CompressFormat compressFormat) { 86 switch (compressFormat) { 87 case JPEG: 88 case WEBP: 89 return "jpg"; 90 case PNG: 91 return "png"; 92 } 93 throw new UnsupportedOperationException("Cannot convert format: " + compressFormat); 94 } 95 } 96