1 package com.bumptech.glide.load.resource.bitmap; 2 3 import android.graphics.Bitmap; 4 import android.util.Log; 5 6 import com.bumptech.glide.load.ResourceEncoder; 7 import com.bumptech.glide.load.engine.Resource; 8 import com.bumptech.glide.util.LogTime; 9 import com.bumptech.glide.util.Util; 10 11 import java.io.OutputStream; 12 13 /** 14 * An {@link com.bumptech.glide.load.ResourceEncoder} that writes {@link android.graphics.Bitmap}s to 15 * {@link java.io.OutputStream}s. 16 * 17 * <p> 18 * {@link android.graphics.Bitmap}s that return true from {@link android.graphics.Bitmap#hasAlpha()}} are written 19 * using {@link android.graphics.Bitmap.CompressFormat#PNG} to preserve alpha and all other bitmaps are written 20 * using {@link android.graphics.Bitmap.CompressFormat#JPEG}. 21 * </p> 22 * 23 * @see android.graphics.Bitmap#compress(android.graphics.Bitmap.CompressFormat, int, java.io.OutputStream) 24 */ 25 public class BitmapEncoder implements ResourceEncoder<Bitmap> { 26 private static final String TAG = "BitmapEncoder"; 27 private static final int DEFAULT_COMPRESSION_QUALITY = 90; 28 private Bitmap.CompressFormat compressFormat; 29 private int quality; 30 31 public BitmapEncoder() { 32 this(null, DEFAULT_COMPRESSION_QUALITY); 33 } 34 35 public BitmapEncoder(Bitmap.CompressFormat compressFormat, int quality) { 36 this.compressFormat = compressFormat; 37 this.quality = quality; 38 } 39 40 @Override 41 public boolean encode(Resource<Bitmap> resource, OutputStream os) { 42 final Bitmap bitmap = resource.get(); 43 44 long start = LogTime.getLogTime(); 45 Bitmap.CompressFormat format = getFormat(bitmap); 46 bitmap.compress(format, quality, os); 47 if (Log.isLoggable(TAG, Log.VERBOSE)) { 48 Log.v(TAG, "Compressed with type: " + format + " of size " + Util.getBitmapByteSize(bitmap) + " in " 49 + LogTime.getElapsedMillis(start)); 50 } 51 return true; 52 } 53 54 @Override 55 public String getId() { 56 return "BitmapEncoder.com.bumptech.glide.load.resource.bitmap"; 57 } 58 59 private Bitmap.CompressFormat getFormat(Bitmap bitmap) { 60 if (compressFormat != null) { 61 return compressFormat; 62 } else if (bitmap.hasAlpha()) { 63 return Bitmap.CompressFormat.PNG; 64 } else { 65 return Bitmap.CompressFormat.JPEG; 66 } 67 } 68 69 } 70