Base64和图片之间的转换,及压缩-java(base64字符串最好代码生成,网页工具存在空格问题)

2023-11-01

1.图片转base64String

public static BufferedImage photoToBase644(String url) {
		String result = "";
        try {
        	//File file = new File(url);
        	File file = new File("C:\\Users\\yuanyuan.song\\Desktop\\photo\\1.jpg");
            InputStream stream1 = new FileInputStream(file);
        	
        	byte[] data = new byte[stream1.available()];
            stream1.read(data);
            stream1.close();
			// 对字节数组Base64编码
            BASE64Encoder encoder = new BASE64Encoder();
            result = encoder.encode(data);
        	//字符过长打印不全
            //System.out.println("图片:"+result );
            log.info("图片:"+result );
            
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result ;
    }

Base64处理的字符串过长,注意获取全

2.Base64转图片

public static boolean GenerateImage(String imgStr, String imgFilePath) {
        if (imgStr == null) // 图像数据为空
            return false;
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            // Base64解码
            byte[] bytes = decoder.decodeBuffer(imgStr);
            for (int i = 0; i < bytes.length; ++i) {
                if (bytes[i] < 0) {// 调整异常数据
                    bytes[i] += 256;
                }
            }
            // 生成jpeg图片
            OutputStream out = new FileOutputStream(imgFilePath);
            out.write(bytes);
            out.flush();
            out.close();
            return true;
        } catch (Exception e) {
            return false;
        }
    }

3.Base64图片压缩

用到的依赖

<dependency>
    <groupId>net.coobird</groupId>
    <artifactId>thumbnailator</artifactId>
    <version>0.4.8</version>
</dependency>

说明:base64的String最好代码生成,否则ImageIO.read(stream)会出错

Base64图片压缩

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.DecimalFormat;
import java.util.Base64;
import javax.imageio.ImageIO;
import com.othp.core.dto.ImageObject;

import lombok.extern.slf4j.Slf4j;
import net.coobird.thumbnailator.Thumbnails;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public static String resizeImageTo40K(String base64Img) {
        try {
        	BufferedImage src = base64String2BufferedImage(base64Img); 
            if (base64Img.length() - base64Img.length() / 8 * 2 > 10000) {
            	DecimalFormat dF = new DecimalFormat("0.00000000");
            	String db = dF.format((float)10000/base64Img.length());		
            	BufferedImage output = Thumbnails.of(src).scale(new Double(db)).asBufferedImage();
            	base64Img = imageToBase64(output);
            }
            return base64Img;
        } catch (Exception e) {
        	System.out.println(e);
            return "";
        }
    }

Base64转BufferedImage

public static BufferedImage base64String2BufferedImage(String base64string) {
        BufferedImage image = null;
        try {         
            InputStream stream = base64StringToInputStream(base64string);
            image = javax.imageio.ImageIO.read(stream);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return image;
    }

Base64转InputStream

private static InputStream base64StringToInputStream(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;
        
    }

BufferedImage转换成base64

public static String imageToBase64(BufferedImage bufferedImage) {
    	org.apache.commons.codec.binary.Base64 encoder = new org.apache.commons.codec.binary.Base64();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
        	javax.imageio.ImageIO.write(bufferedImage, "jpg", baos);
        } catch (Exception e) {
        	System.out.println(e);
        }
        return new String(encoder.encode((baos.toByteArray())));
    }

总结的问题
javax.imageio.ImageIO.read(stream)为null
1.后来在网上查找ImageIO用法知道,它可读取的图片类型是有限制的,可以读取图片的格式为:[BMP, bmp, jpg, JPG, wbmp, jpeg, png, PNG, JPEG, WBMP, GIF, gif]
2.可是文件后缀是jpg格式,按道理说应该支持啊,后来将文件下载下来放到notepad++上查看才发现前缀是:RIFF? WEBPVP8 这说明该文件的实际格式是webp格式.
3.文件后缀名有时候不是实际的文件格式.
4.不推荐java代码处理,前端直接压缩后给后端

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Base64和图片之间的转换,及压缩-java(base64字符串最好代码生成,网页工具存在空格问题) 的相关文章

随机推荐