1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
|
public class WebpImageView extends ImageView {
public static final boolean NATIVE_WEB_P_SUPPORT = Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2;
public WebpImageView(Context context) { super(context); init(context, null); }
public WebpImageView(Context context, AttributeSet attrs) { super(context, attrs); init(context, attrs); }
public WebpImageView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(context, attrs); }
private void init(Context context, AttributeSet attrs) { TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.webp);
int webpSourceResourceID = a.getResourceId(R.styleable.webp_webp_src, 0); a.recycle();
InputStream inputStream = getResources().openRawResource(webpSourceResourceID); byte[] bytes = streamToBytes(inputStream); Bitmap bitmap = null;
if (!NATIVE_WEB_P_SUPPORT) { bitmap = WebPDecoder.getInstance().decodeWebP(bytes); } else { bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length); } this.setImageBitmap(bitmap); }
private static byte[] streamToBytes(InputStream is) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); int i = -1; try { byte[] bytes = new byte[1024]; while ((i = is.read(bytes)) != -1) { baos.write(bytes, 0, i); bytes = new byte[1024]; } return baos.toByteArray(); } catch (Exception e) { } return null; } }
|