android P ImageDecoder 使用

本文参考自官方文档,链接如下:

一个的可以将PNG, JPEG, WEBP, GIF, or HEIF 格式的图片的转换成Drawable 或者Bitmap 对象的类。
要使用它, 首先使用createSource 创建一个source, 例如解码一个文件使用createSource(File) ,将返回值传入decodeDrawable(Source) 或者 decodeBitmap(Source):

 File file = new File(...);
  ImageDecoder.Source source = ImageDecoder.createSource(file);
  Drawable drawable = ImageDecoder.decodeDrawable(source);

source是可以复用的方需要,将图片解码成不同的形态,例如修改宽高。

第二方法还可以传递OnHeaderDecodedListener,这里ImageInfo存放的是原始的图片的宽和高。可以修改用来修改图片宽高的时候修改SampleSize。

 OnHeaderDecodedListener listener = new OnHeaderDecodedListener() {
      public void onHeaderDecoded(ImageDecoder decoder, ImageInfo info, Source source) {
          decoder.setTargetSampleSize(2);
      }
  };
  Drawable drawable = ImageDecoder.decodeDrawable(source, listener);

如果要解码的图片是gif,会被解码成AnimatedImageDrawable 使用方法如下:

  Drawable drawable = ImageDecoder.decodeDrawable(source);
  if (drawable instanceof AnimatedImageDrawable) {
      ((AnimatedImageDrawable) drawable).start();
  }

默认解码出来的bitmap是不可变,但是仍然可以使用PostProcessor来添加一些自定义的效果,例如:

  Drawable drawable = ImageDecoder.decodeDrawable(source, (decoder, info, src) -> {
      decoder.setPostProcessor((canvas) -> {
              // This will create rounded corners.
              //创建圆角照片
              Path path = new Path();
              path.setFillType(Path.FillType.INVERSE_EVEN_ODD);
              int width = canvas.getWidth();
              int height = canvas.getHeight();
              path.addRoundRect(0, 0, width, height, 20, 20, Path.Direction.CW);
              Paint paint = new Paint();
              paint.setAntiAlias(true);
              paint.setColor(Color.TRANSPARENT);
              paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC));
              canvas.drawPath(path, paint);
              return PixelFormat.TRANSLUCENT;
      });
  });

如果解码的照片是不完整的或者包含错误,解码的时候会抛出DecodeException,一些情况下,可能已经解码出一部分的照片,这个时候传递OnPartialImageListener ,并返回true,就只显示解码出来的部分,剩余部分使用空白代替。

 Drawable drawable = ImageDecoder.decodeDrawable(source, (decoder, info, src) -> {
      decoder.setOnPartialImageListener((DecodeException e) -> {
              // Returning true indicates to create a Drawable or Bitmap even
              // if the whole image could not be decoded. Any remaining lines
              // will be blank.
              return true;
      });
  });

有错误的地方,欢迎指正,谢谢。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值