zoukankan      html  css  js  c++  java
  • 【android】 如何把gif图片下载到本地

    以上图片大家可以看到,虽然是个jpg格式的文件,但是本质上是个动图。

    但是发现在咱的图片模块下,本地存储的图片只有一帧,问题出在哪里呢?

    http获取到的byte[]数据是没问题的

    断点跟踪了下,发现问题出现在最后一句压缩图片尺寸的时候。

    public static Bitmap getScaledBitMap(byte[] data, int width, int height) {
    
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            BitmapFactory.decodeByteArray(data, 0, data.length, options);
    
            float srcWidth = options.outWidth;
            float srcHeight = options.outHeight;
            int inSampleSize = 1;
    
            if (srcHeight > height || srcWidth > width) {
                if (srcWidth > srcHeight)
                    inSampleSize = Math.round(srcHeight / height);
                else
                    inSampleSize = Math.round(srcWidth / width);
            }
    
            options = new BitmapFactory.Options();
            options.inSampleSize = inSampleSize;
    
            return BitmapFactory.decodeByteArray(data, 0, data.length, options);
        }

    最后的解决之道是,不经过Bitmap,直接把http获取到的byte[]数据写入到本地;在取出的时候,才进行图片尺寸压缩。

     /**
         * 写入bytes
         *
         * @param url
         * @param bytes
         * @return
         */
        public boolean save(String url, byte[] bytes) {
            if (bytes == null || bytes.length == 0)
                return false;
    
            url = trans2Local(url);
            File file = new File(url);
    
            if (file.exists())
                return true;
    
            ZIO.createNewFile(file);
            FileOutputStream fos = null;
            try {
                fos = new FileOutputStream(file);
                fos.write(bytes);
                return true;
            } catch (Exception e) {
                e.printStackTrace();
                Log.e("存储出错", e.getMessage());
            } finally {
                try {
                    fos.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            return false;
        }

    这种做法额外的好处是,不再理会奇怪的图片格式质量问题。

     比如我们用Bitmap保存图片的时候还要取判断图片类型,还要去指定压缩精度(如果100的话图片尺寸比原图还要大很多,真奇怪)

        Bitmap.CompressFormat format = url.toLowerCase().indexOf("png") > 0 ? Bitmap.CompressFormat.PNG : Bitmap.CompressFormat.JPEG;
        bitmap.compress(format, 75, fos);
  • 相关阅读:
    MAC终端配置
    SCIENCE公布125个科学前沿问题
    【Python3】内存释放机制
    【Python3】装饰器
    【Python3】迭代器&装饰器
    【Python3】内置函数
    【Python3】高阶函数
    【Python3】匿名函数
    【Python3】递归函数
    【Python3】嵌套函数
  • 原文地址:https://www.cnblogs.com/kimmy/p/4780024.html
Copyright © 2011-2022 走看看