【图片URL、图片文件转base64】与【图片URL、图片文件压缩字节流后再转base64】

图片直接转base64

图片转base64,有很多参考代码,包括一些在线工具(例如http://www.jsons.cn/img2base64/):
请添加图片描述
该图片的base64结果基本如下(省略返回结果):

data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABQAAAAMACAIAAAD0Vl2aAAEAAElEQVR4nHz9S5bsSpIkCBKJ2

代码:

public class ImageUtil {


    /**
     * base64Image方法
     * 将网络图片编码为base64
     */
   public static String base64Image(String url) {
        if (url.indexOf("http") > -1) {
            String base64 = factoryBase(url);
            if (StringUtils.isNotBlank(base64)) {
                return resizeImageTo200K(base64);
            }
        }
        return "";
    }
    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 "";
        }
    }

 
    public static BufferedImage base64String2BufferedImage(String base64string) {
        BufferedImage image = null;
        try {
            InputStream stream = BaseToInputStream(base64string);
            image = ImageIO.read(stream);
        } catch (IOException e) {
            return null;
        }
        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 resizeImageTo200K(String base64Img) {
        try {
            BufferedImage src = base64String2BufferedImage(base64Img);
            BufferedImage output = Thumbnails.of(src).size(src.getWidth() / 2, src.getHeight() / 2).asBufferedImage();
            String base64 = imageToBase64(output);
            if (base64.length() - base64.length() / 8 * 2 > 200000) {
                output = Thumbnails.of(output).scale(1 / (base64.length() / 200000)).asBufferedImage();
                base64 = imageToBase64(output);
            }
            return base64;
        } catch (Exception e) {
            return base64Img;
        }
    }
}    

图片文件字节流压缩后再转base64(这里使用Deflater压缩算法)


public class ImageBaseUtil {

    /**
     * 根据图片链接转为base64数据
     */
    public static String getBase64ByUrl(String imageUrl) {
        try {
            // new一个URL对象
            URL url = new URL(imageUrl);
            // 打开链接
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            // 设置请求方式为"GET"
            conn.setRequestMethod("GET");
            // 超时响应时间为5秒
            conn.setConnectTimeout(5 * 1000);
            // 通过输入流获取图片数据
            byte[] data = null;
            try {
                InputStream in = conn.getInputStream();
                ByteArrayOutputStream outStream = new ByteArrayOutputStream();
                byte[] buffer = new byte[1024];
                int len = 0;
                while ((len = in.read(buffer)) != -1) {
                    outStream.write(buffer, 0, len);
                }
                in.close();
                data = outStream.toByteArray();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            Base64.Encoder encoder = Base64.getEncoder();
            try {
//                System.out.println(encoder.encodeToString(compress(data)));
                return encoder.encodeToString(compress(data));
            } catch (IOException e) {
                return null;
            }
        } catch (Exception e) {
            return null;
        }

    }

    public static byte[] compress(byte[] inputByte) throws IOException {
        int len = 0;
        Deflater defl = new Deflater();
        defl.setInput(inputByte);
        defl.finish();
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte[] outputByte = new byte[1024];
        try {
            while (!defl.finished()) {
                // 压缩并将压缩后的内容输出到字节输出流bos中
                len = defl.deflate(outputByte);
                bos.write(outputByte, 0, len);
            }
            defl.end();
        } finally {
            bos.close();
        }
        return bos.toByteArray();
    }

}

该图片的base64结果基本如下(省略返回结果):

eJyct3dUk18QKBgIJHQpoYXeQ5USpImEktAhoRN6D6F3wUKTFhIJVUDQUA1VQBBQUJQqvQREQFGqgIIFVKyP39s9u2//2PPO7v3m

工具类

package com.jd.jr.pension.account.jsf.common.util;

import org.apache.commons.codec.binary.Base64;
import sun.misc.BASE64Decoder;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URL;
import java.util.zip.Deflater;

public class ImageUtil {

    /**
     * 将图片转换为base64格式
     *
     * @param imageUrl:图片路径
     * @param sizeLimit:原图大小上限,当图片原图大小超过该值时先将图片大小 设置为该值以下再转换成base64格式,单位kb
     * @return
     */
    public static String convertImageToBase64(String imageUrl, Integer sizeLimit) {
        // 默认上限为500k
        if (sizeLimit == null) {
            sizeLimit = 200;
        }
        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) {
            // 抛出异常
            return null;
        } 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;
    }


    // 字节压缩
    public static byte[] compress(byte[] inputByte) throws IOException {
        int len = 0;
        Deflater defl = new Deflater();
        defl.setInput(inputByte);
        defl.finish();
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte[] outputByte = new byte[1024];
        try {
            while (!defl.finished()) {
                // 压缩并将压缩后的内容输出到字节输出流bos中
                len = defl.deflate(outputByte);
                bos.write(outputByte, 0, len);
            }
            defl.end();
        } finally {
            bos.close();
        }
        return bos.toByteArray();
    }


    public static String base64ToBase64ViaDeflater(String base64Img) {
        try {
            Base64 encoder = new Base64();
            BASE64Decoder decoder = new BASE64Decoder();
            String res = encoder.encodeToString(compress(decoder.decodeBuffer(base64Img)));
            return res;
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * Image转BufferedImage
     *
     * @param image
     * @return
     */
    public static BufferedImage toBufferedImage(Image image) {
        if (image instanceof BufferedImage) {
            return (BufferedImage) image;
        }

        // This code ensures that all the pixels in the image are loaded
        image = new ImageIcon(image).getImage();

        // Determine if the image has transparent pixels; for this method's
        // implementation, see e661 Determining If an Image Has Transparent Pixels
        //boolean hasAlpha = hasAlpha(image);

        // Create a buffered image with a format that's compatible with the screen
        BufferedImage bimage = null;
        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
        try {
            // Determine the type of transparency of the new buffered image
            int transparency = Transparency.OPAQUE;
	       /* if (hasAlpha) {
	         transparency = Transparency.BITMASK;
	         }*/

            // Create the buffered image
            GraphicsDevice gs = ge.getDefaultScreenDevice();
            GraphicsConfiguration gc = gs.getDefaultConfiguration();
            bimage = gc.createCompatibleImage(
                    image.getWidth(null), image.getHeight(null), transparency);
        } catch (HeadlessException e) {
            // The system does not have a screen
        }

        if (bimage == null) {
            // Create a buffered image using the default color model
            int type = BufferedImage.TYPE_INT_RGB;
            //int type = BufferedImage.TYPE_3BYTE_BGR;//by wang
	        /*if (hasAlpha) {
	         type = BufferedImage.TYPE_INT_ARGB;
	         }*/
            bimage = new BufferedImage(image.getWidth(null), image.getHeight(null), type);
        }

        // Copy image to buffered image
        Graphics g = bimage.createGraphics();

        // Paint the image onto the buffered image
        g.drawImage(image, 0, 0, null);
        g.dispose();

        return bimage;
    }


    /**
     * 将图片转换为压缩过过字节流的base64格式
     *
     * @param imageUrl:图片路径
     * @param sizeLimit:原图大小上限,当图片原图大小超过该值时先将图片大小 设置为该值以下再转换成base64格式,单位kb
     * @return
     */
    public static String convertImageToBase64ViaDeflater(String imageUrl, Integer sizeLimit) {
        // 默认上限为500k
        if (sizeLimit == null) {
            sizeLimit = 200;
        }
        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);
            base64Image = Base64.encodeBase64String(compress(data));
        } catch (Exception e) {
            // 抛出异常
            return null;
        } 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;
    }

}

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值