首页 > 编程语言 > 详细

java中图片文件和base64编码的转换

时间:2019-12-25 15:59:47      阅读:102      评论:0      收藏:0      [点我收藏+]

在线图片转base64编码

  import javax.imageio.ImageIO;
  import java.awt.image.BufferedImage;
  import java.io.ByteArrayOutputStream;
  import java.io.IOException;
  import java.net.URL;
  import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
  /**
     * 下载图片并转换成base64格式
     *
     * @param imageUrl 图片URL
     *
     * @return 图片base64编码
     */
    private String downLoadImageToBase64(String imageUrl) throws Exception{
        logger.info("chainserviceImpl.downLoadImageToBase64,start,imageUrl:{}",imageUrl);
        if(StringUtils.isBlank(imageUrl)){
            throw new JobException("人脸识别,人脸图片url不能为空");
        }
        //下载图片
        BufferedImage image =null;
        URL url = new URL(imageUrl);
        image = ImageIO.read(url);

        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        String type = StringUtils.substring(imageUrl, imageUrl.lastIndexOf(".") + 1);
        ImageIO.write(image, type, bos);
        byte[] imageBytes = bos.toByteArray();
        String imageString = Base64.encode(imageBytes);
        bos.close();
        logger.info("chainserviceImpl.downLoadImageToBase64,end,imageUrl:{}",imageUrl);

        if(StringUtils.isBlank(imageString)){
            throw new JobException("获取人脸图片base64编码失败");
        }
        return imageString;
    }

本地图片转base64编码

  import java.nio.file.Files;
  import java.nio.file.Paths;  
  import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
  /**
     * 本地图片转base64编码
     * 
     * @param filePath 文件图片所在路径
     *                 
     * @return base64编码
     */
    public String imageToBase64(String filePath) throws Exception{
        if(StringUtils.isBlank(filePath)){
            return null;
        }
        String encode="";
        try{
            byte[] bytes = Files.readAllBytes(Paths.get(filePath));
            encode = Base64.encode(bytes);
        }catch (Exception e){
            throw e;
        }
        return encode;
    }

base64编码转图片

    import java.nio.file.Files;
    import java.nio.file.Paths;
    import java.nio.file.StandardOpenOption;

    /**
     * base64编码转成图片文件
     * 
     * @param base64 图片的base64编码
     * @param filePath 图片文件的保存路径
     *                 
     * @return 
     * @throws Exception
     */
    public static String decryptByBase64(String base64, String filePath) throws Exception{
        if (base64 == null && filePath == null) {
            return "生成文件失败,请给出相应的数据。";
        }
        try {
            Files.write(Paths.get(filePath),Base64.decode(base64), StandardOpenOption.CREATE);
        } catch (IOException e) {
            throw e;
        }
        return "指定路径下生成文件成功!";
    }

java中图片文件和base64编码的转换

原文:https://www.cnblogs.com/htyj/p/12096696.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!