介绍多张图片压缩转Bas64速度优化问题

今天项目有一个需求,要求多张图片上传,并且时间在7秒左右,废话不多说上效果图
效果图
我解决的方案有二种:

  1. 第一种是用线程的方式去上传图片,结果发现同时压缩4M的图非常的慢,以及中途转Bas64用时20多秒,当然这根据机型而定,代码非常的简单我还是贴出来:
StringBuffer stringBuffer = new StringBuffer();
            for (int i = 0; i < list.size(); i++) {
                Bitmap bitmap = getBitmap(list.get(i));
                String path = SaveBitmap(bitmap, i);
//                fileList.add(path);
                Bitmap bitmapNew = ImageUtil.getLocalBitmap(path);
                String photoString = NativeUtil.getcomImageBase64(bitmapNew);
                stringBuffer.append(photoString).append(",");
            }
           String mIamgeString = stringBuffer.toString().substring(0, stringBuffer.length() - 1);`

2.第二种方式是用AsyncTask,我直接贴代码了:

package com.sdy.zhuanqianbao.kit;
import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Environment;
import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by csl on 2017/8/17.
 */

public class CompressPhotoUtils {

    private List<String> fileList = new ArrayList<>();
    private ProgressDialog progressDialog;
    private static File file;

    public void CompressPhoto(Context context, List<String> list, CompressCallBack callBack) {
        CompressTask task = new CompressTask(context, list, callBack);
        task.execute();
    }

    class CompressTask extends AsyncTask<Void, Integer, String> {
        private Context context;
        private List<String> list;
        private CompressCallBack callBack;

        CompressTask(Context context, List<String> list, CompressCallBack callBack) {
            this.context = context;
            this.list = list;
            this.callBack = callBack;

            if (DeviceUtils.isExitsSdcard()) {
                String filePath = Environment.getExternalStorageDirectory() + "/huizhuan/upload";
                file = new File(filePath);
            }
        }

        /**
         * 运行在UI线程中,在调用doInBackground()之前执行
         */
        @Override
        protected void onPreExecute() {
//            progressDialog = ProgressDialog.show(context, null, "处理中...");
        }

        /**
         * 后台运行的方法,可以运行非UI线程,可以执行耗时的方法
         */
        @Override
        protected String doInBackground(Void... params) {
            StringBuffer stringBuffer = new StringBuffer();
            for (int i = 0; i < list.size(); i++) {
                Bitmap bitmap = getBitmap(list.get(i));
                String path = SaveBitmap(bitmap, i);
//                fileList.add(path);
                Bitmap bitmapNew = ImageUtil.getLocalBitmap(path);
                String photoString = NativeUtil.getcomImageBase64(bitmapNew);
                stringBuffer.append(photoString).append(",");
            }
           String mIamgeString = stringBuffer.toString().substring(0, stringBuffer.length() - 1);

            if (file.exists()){
                FileUtils.delete(file);
            }

            return mIamgeString;
        }

        /**
         * 运行在ui线程中,在doInBackground()执行完毕后执行
         */
        @Override
        protected void onPostExecute(String imageString) {
//            progressDialog.dismiss();
            callBack.success(imageString);
        }

        /**
         * 在publishProgress()被调用以后执行,publishProgress()用于更新进度
         */
        @Override
        protected void onProgressUpdate(Integer... values) {
        }
    }

    /**
     * 从sd卡获取压缩图片bitmap
     */
    public static Bitmap getBitmap(String srcPath) {
        BitmapFactory.Options newOpts = new BitmapFactory.Options();
        newOpts.inJustDecodeBounds = true;
        Bitmap bitmap = BitmapFactory.decodeFile(srcPath, newOpts);
        newOpts.inJustDecodeBounds = false;
        int w = newOpts.outWidth;
        int h = newOpts.outHeight;
        float hh = 800f;
        float ww = 480f;
        // 缩放比。由于是固定比例缩放,只用高或者宽其中一个数据进行计算即可
        int be = 1;// be=1表示不缩放
        if (w > h && w > ww) {// 如果宽度大的话根据宽度固定大小缩放
            be = (int) (newOpts.outWidth / ww);
        } else if (w < h && h > hh) {// 如果高度高的话根据宽度固定大小缩放
            be = (int) (newOpts.outHeight / hh);
        }
        newOpts.inSampleSize = be;// 设置缩放比例
        bitmap = BitmapFactory.decodeFile(srcPath, newOpts);
        return bitmap;
    }

    /**
     * 保存bitmap到内存卡
     */
    public static String SaveBitmap(Bitmap bmp, int num) {

        String path = null;
        if (!file.exists()){
            file.mkdirs();
        }

        try {
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String picName = formatter.format(new Date());
            path = file.getPath() + "/" + picName + "-" + num + ".jpg";
            FileOutputStream fileOutputStream = new FileOutputStream(path);
            bmp.compress(Bitmap.CompressFormat.JPEG, 50, fileOutputStream);
            fileOutputStream.flush();
            fileOutputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return path;
    }

    public interface CompressCallBack {
        void success(String imageString);
    }
}

然后Activity里面主要用:

 //图片转base64
        if (listImgPath.size() != 0) {
            new CompressPhotoUtils().CompressPhoto(MarketFeedBackActivity.this, listImgPath, new
                    CompressPhotoUtils.CompressCallBack() {
                        @Override
                        public void success(String imageString) {
                            upload(imageString);  //执行上传的方法
                        }
                    });
        }

这样就完成了,从20多秒变成5-6秒就成功上传图片了,从数据库里面成功看到上传完成以后数据库这里写图片描述
作者:工程师丶佛爷
有更好的优化方案欢迎留言,谢谢.

### 回答1: 可以使用uniapp内置的base64图片方法,具体步骤如下: 1. 在template中使用image标签,设置src属性为base64字符串。 2. 在script中使用uni.base64ToArrayBuffer方法将base64字符串为ArrayBuffer类型。 3. 使用uni.getImageInfo方法获取图片信息,包括宽度和高度。 4. 使用uni.canvasToTempFilePath方法将ArrayBuffer类型的图片为临时文件路径。 5. 将临时文件路径赋值给image标签的src属性,即可显示图片。 示例代码如下: <template> <view> <image :src="imgSrc"></image> </view> </template> <script> export default { data() { return { base64Str: 'base64字符串', imgSrc: '' } }, methods: { async base64ToImg() { const arrayBuffer = await uni.base64ToArrayBuffer(this.base64Str) const { width, height } = await uni.getImageInfo({ src: this.base64Str }) const tempFilePath = await uni.canvasToTempFilePath({ x: , y: , width, height, destWidth: width, destHeight: height, canvasId: 'canvas', fileType: 'jpg', quality: 1, data: arrayBuffer }) this.imgSrc = tempFilePath.tempFilePath } }, mounted() { this.base64ToImg() } } </script> ### 回答2: 在uniapp中,我们可以将一张图片编码为base64格式的字符串,然后将其在页面中进行显示。同时,我们也可以将一个base64格式的字符串换为一张图片。 通过使用uniapp内置的Base64模块,我们可以方便地将图片数据编码为base64格式的字符串。具体的步骤如下: 1. 获取图片数据。 我们可以通过uniapp提供的API获取本地文件系统中的图片数据。例如,以下代码可以获取并读取图片: ``` uni.chooseImage({ success: function (res) { var tempFilePath = res.tempFilePaths[0]; uni.getFileSystemManager().readFile({ filePath: tempFilePath, encoding: 'base64', success: function (res) { var base64 = 'data:image/jpeg;base64,' + res.data; } }); } }); ``` 2. 将图片数据编码为base64格式的字符串。 在获取到图片数据之后,我们可以借助Base64模块将其编码为base64格式的字符串。具体的代码如下: ``` var base64 = uni.base64ToArrayBuffer(res.data); var binary = ''; var bytes = new Uint8Array(base64); var len = bytes.byteLength; for (var i = 0; i < len; i++) { binary += String.fromCharCode(bytes[i]); } var base64String = btoa(binary); ``` 3. 将base64格式的字符串换为图片。 我们可以将一个base64格式的字符串换为一张图片,并将其展示在页面中。具体的代码如下: ``` <img :src="base64String"/> ``` 通过以上步骤,我们可以在uniapp中实现将base64格式的图片字符串换为图片并显示到页面上的功能。同时,我们也可以将一张图片编码为base64格式的字符串并进行传输和处理。这种方法通常用于在移动端进行图片显示和上传等操作。 ### 回答3: Uniapp是一个跨平台的开发框架,它可以让开发者使用一套代码编写出同时适用于iOS、Android和H5的应用程序。在Uniapp中,我们可以通过将图片采用base64编码的方式存储在后台,然后直接将base64字符串传递到前端,最后通过js的方式将base64字符串换为可被浏览器渲染并显示的图片。 具体操作流程如下: 1. 后台将图片换为base64编码,将其保存在数据库中或者直接传递到前端。在后台中可以使用Python等语言的base64库将图片换为base64编码。 2. 前端接收到base64字符串后,使用以下JS代码将其换为图片并显示: ``` // 将base64字符串换为ArrayBuffer var arr = btoa(base64String); var binary_string = window.atob(arr); var len = binary_string.length; var bytes = new Uint8Array(len); for (var i = 0; i < len; i++) { bytes[i] = binary_string.charCodeAt(i); } var blob = new Blob([bytes.buffer], { type: "image/png" }); // 在html中添加img标签并显示图片 var objUrl = URL.createObjectURL(blob); var img = document.createElement("img"); img.src = objUrl; // 将img标签添加到需要显示的dom节点中 ``` 以上代码将base64字符串换为ArrayBuffer、Blob和ObjectURL等格式,并最终显示在浏览器中。 需要注意一点的是,在使用base64编码的图片时,会占用更多的内存,因此在使用时应注意优化图片尺寸和压缩比例。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值