图片压缩解决无法显示问题,图片转Base64过大传到第三方或前端无法显示问题解决方案

平时我们转图片为Base64会生成一个长长的字符串,然后将这个字符串传改前台或者是第三方服务会出现显示不了,报错的问题。

 解决方案代码如下:

/**
     * 将图片转换为base64格式
     *
     * @param imageUrl:图片路径
     * @param sizeLimit:原图大小上限,当图片原图大小超过该值时先将图片大小 设置为该值以下再转换成base64格式,单位kb
     * @return
     */
    public static String convertImageToBase64(String imageUrl, Integer sizeLimit) throws IOException {
        // 默认上限为500k
        if (sizeLimit == null) {
            sizeLimit = 500;
        }
        sizeLimit = sizeLimit * 1024;
        String base64Image;
        DataInputStream dataInputStream = null;
        ByteArrayOutputStream outputStream = null;
        ByteArrayInputStream inputStream = null;
        try {
            // 从远程读取图片
            URL url = new URL(imageUrl);
            dataInputStream = new DataInputStream(url.openStream());
            outputStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[2048];
            int length;
            while ((length = dataInputStream.read(buffer)) > 0) {
                outputStream.write(buffer, 0, length);
            }
            byte[] context = outputStream.toByteArray();

            // 将图片数据还原为图片
            inputStream = new ByteArrayInputStream(context);
            //图片可能变色
            //BufferedImage image = ImageIO.read(inputStream);
            //使用该方法解决 图片压缩变色问题  ImageIO.read()会存在图片变色问题
            Image src = Toolkit.getDefaultToolkit().getImage(url);
            BufferedImage image = toBufferedImage(src);
            int imageSize = context.length;
            int type = image.getType();
            int height = image.getHeight();
            int width = image.getWidth();

            BufferedImage tempImage;
            // 判断文件大小是否大于size,循环压缩,直到大小小于给定的值

            System.out.println(sizeLimit);
            while (imageSize > sizeLimit) {
                System.err.println(imageSize);
                // 将图片长宽压缩到原来的90%
                height = new Double(height * 0.9).intValue();
                width = new Double(width * 0.9).intValue();
                tempImage = new BufferedImage(width, height, type);
                // 绘制缩小后的图
                tempImage.getGraphics().drawImage(image, 0, 0, width, height, null);
                // 重新计算图片大小
                outputStream.reset();
                ImageIO.write(tempImage, "jpg", outputStream);
                imageSize = outputStream.toByteArray().length;

            }

            // 将图片转化为base64并返回
            byte[] data = outputStream.toByteArray();
            // 此处一定要使用org.apache.tomcat.util.codec.binary.Base64,防止再linux上出现换行等特殊符号
            base64Image = Base64.encodeBase64String(data);
        } catch (Exception e) {
            // 抛出异常
            throw e;
        } finally {
            if (dataInputStream != null) {
                try {
                    dataInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return base64Image;
    }

感谢

M-Kundera的分享学习到了。希望可以帮助到各位,一起强起来。

  • 0
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答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、付费专栏及课程。

余额充值