将网络图片编码为base64

 1、工具类

package com.task.test.utils;


import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.codec.binary.Base64;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @Date 2023/1/10
 * @Author liuziyan
 * @description
 */
public class ImageService {


    public static void main(String[] args) {
        String s = ImageService.factoryBase("https://vod-cover-wvqt.gdoss.xstore.ctyun.cn/a6e099d6f8f54494b0f6b1c8b13b201c.jpg");
        System.out.println(s);
    }

    public static String factoryBase(String StoragePath) {
        try {
            URL url = new URL(StoragePath);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5 * 1000);
            InputStream inStream = conn.getInputStream();
            ByteArrayOutputStream outStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = inStream.read(buffer)) != -1) {
                outStream.write(buffer, 0, len);
            }
            inStream.close();
            byte[] data = outStream.toByteArray();
            BASE64Encoder encoder = new BASE64Encoder();
            String base64 = encoder.encode(data);
            return base64;
        } catch (Exception e) {
            return "";
        }
    }
    /**
     * 将网络图片编码为base64
     *
     * @return
     * @throws
     */
    public static String base64Image(String url) {
        if (url.indexOf("http") > -1) {
            String base64 = factoryBase(url);
            if (base64 != "") {
                return resizeImageTo40K(base64);
            }
        }
        return "";
    }


    public static BufferedImage base64String2BufferedImage(String base64string) {
        BufferedImage image = null;
        try {
            InputStream stream = BaseToInputStream(base64string);
            image = ImageIO.read(stream);
        } catch (IOException e) {
        }
        return image;
    }
//    BufferedImage转换成base64,在这里需要设置图片格式,如下是jpg格式图片:

    public static String imageToBase64(BufferedImage bufferedImage) {
        Base64 encoder = new Base64();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            ImageIO.write(bufferedImage, "jpg", baos);
        } catch (IOException e) {
        }
        return new String(encoder.encode((baos.toByteArray())));
    }

    private static InputStream BaseToInputStream(String base64string) {
        ByteArrayInputStream stream = null;
        try {
            BASE64Decoder decoder = new BASE64Decoder();
            byte[] bytes1 = decoder.decodeBuffer(base64string);
            stream = new ByteArrayInputStream(bytes1);
        } catch (Exception e) {
            // TODO: handle exception
        }
        return stream;
    }

    public static String resizeImageTo40K(String base64Img) {
        try {
            BufferedImage src = base64String2BufferedImage(base64Img);
            BufferedImage output = Thumbnails.of(src).size(src.getWidth() / 3, src.getHeight() / 3).asBufferedImage();
            String base64 = imageToBase64(output);
            if (base64.length() - base64.length() / 8 * 2 > 40000) {
                output = Thumbnails.of(output).scale(1 / (base64.length() / 40000)).asBufferedImage();
                base64 = imageToBase64(output);
            }
            return base64;
        } catch (Exception e) {
            return base64Img;
        }
    }
}

2、测试

@Test
    public void test4() throws IOException {
        String s = ImageService.base64Image("https://vod-cover-wvqt.gdoss.xstore.ctyun.cn/a6e099d6f8f54494b0f6b1c8b13b201c.jpg");
        System.out.println(s);
    }
    @Test
    public void test2() throws IOException {
        //把上边生成的编码存到文件中,再从文件中读取,因为字符串太长了
        FileInputStream input = new FileInputStream("D:\\material\\base64.txt");
        byte[] bytes = IOUtils.toByteArray(input);
        // 用base64解码得到解码后的字节数组
        byte[] decodeBytes = Base64.getDecoder().decode(bytes);
        //把新字节数组输出到文件中
        IOUtils.write(decodeBytes,new FileOutputStream("D:\\material\\123.jpg"));
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值