图片base64编码解码

传参时去掉base64编码开头的“data:image/jpg;base64,”

/**
 * Base64 图片 编码解码
 *
 */
public class Base64Image {
    
    
	
	/**
	 * 对字节数组字符串进行Base64解码,并生成图片
	 * @return
	 */
	public static boolean generateImage(String base64Str,String imgFilePath) {
    
    
		if (base64Str == null) {
    
    
			return false;
		}
		BASE64Decoder decoder = new BASE64Decoder();
		
		try {
    
    
			// base64解码
			byte[] bytes = decoder.decodeBuffer(base64Str);
			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) {
    
    
			e.printStackTrace();
			return false;
		}
	}
}

猜你喜欢

转载自blog.csdn.net/qq_41841482/article/details/114483098