JAVA实现图片与base64字符串之间的转换详解编程语言

 
import java.io.FileInputStream; 
import java.io.FileOutputStream; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.OutputStream; 
 
import sun.misc.BASE64Decoder; 
import sun.misc.BASE64Encoder; 
 
/** 
 * 图片与base64字符串之间的转换 
 * @author yfli 
 * 
 */ 
public class Base64Decoder { 
	/** 
	 * 图片转化成base64字符串   
	 * @param imgFilePath 
	 * @return 
	 */ 
	public static String GetImageStr(String imgFilePath) { 
		byte[] data = null; 
		try { 
			InputStream in = new FileInputStream(imgFilePath); 
			data = new byte[in.available()]; 
			in.read(data); 
			in.close(); 
		} catch (IOException e) { 
			e.printStackTrace(); 
		} 
 
		BASE64Encoder encoder = new BASE64Encoder(); 
		return encoder.encode(data); 
	} 
 
	/** 
	 * base64字符串转化成图片   
	 * @param imgStr 
	 * @param imgFilePath 
	 * @return 
	 */ 
	public static boolean GenerateImage(String imgStr, String imgFilePath) { 
		if (imgStr == null) { 
			return false; 
		} 
		BASE64Decoder decoder = new BASE64Decoder(); 
		try { 
			byte[] bytes = decoder.decodeBuffer(imgStr); 
			for (int i = 0; i < bytes.length; i++) { 
				if (bytes[i] < 0) { 
					int tmp40_38 = i; 
					byte[] tmp40_37 = bytes; 
					tmp40_37[tmp40_38] = (byte) (tmp40_37[tmp40_38] + 256); 
				} 
			} 
 
			OutputStream out = new FileOutputStream(imgFilePath); 
			out.write(bytes); 
			out.flush(); 
			out.close(); 
			return true; 
		} catch (Exception e) { 
		} 
		return false; 
	} 
 
	public static void main(String[] args) { 
		String file = "e:/qiao.png"; 
		System.out.println(GetImageStr(file)); 
		 
		String str = "iVBORw0KGgoAAAANSUhEUgAAAFgAAABjCAIAAACQSlANAAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAA7EAAAOxAGVKw4bAAAPSUlEQVR4nN1cS48lSXX+vpN5q6q7pmkGzTAja7xARi0h8xCIhRGssdmyQEhmy4/xxguLDQtLCAlkdrbYsGCBYIXwxrIsg2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qAlDzJZleIJ/Kq1rBxXkB8efu+oi+c1Duqrxr5Sw71Kin7p7NBYyoLzqvGsybCXizhAGFqb1iDHBV99nEcN0IrRCEefme1uD68xE7OqoU7ZWaQHYSOb2oMHIoZ5Ai9sbOwr2MXet0+iVpZxuhwttflmYzIGm1ZpXX2hIY3AAA29VGFOJc1beOFnTfPConEEPRJvoPFqHfcrAPl/wZnDld9TDZ5Rw9GX4HZRm8qnXdawWobWrcW2gfhtTiTkFj6wjVPrPbOSHCamT+pzJZbqbPKCTtfWje96asucDwg53xx2qjI87XPUY0Otg31dO2lp3ce+FoMhesEswcqBe7RMm+mhmE2QNEduSp/fBVYPxhXqeuCnTc581A2733CjruuaK8jXZB19hqCNpnqBpxVM8odtq9FlOet5q2NnctfbWSt02XlLc+NavfGFkLMaH8jb2LWijvz/O9S/t3HTTHERcM6xYDwjR7fz0PTMo610GNDZ428vdjWiy1dfjSaaQXSDWbKI8eRHbMPKUvvY61WdiIPtq94s0Li5Y1ZwbC5jfqalejeapuS7uKufj69jUMoxNZz0Y1xwvXS1fd4NmL2AnGysi6etc031xG7tdMjXOW2wV7p5XYslG6LYiqyxRtZIq+bkYWPO1xYqZZ1Auterajc7+wi8kiEOF3hGI/S1kor6+6G37BWewFLXDHHrFnL0xM58jyIcNyNzh7UOwR2+xJe2aodtONSylwe+cnwbgl8Lte2lMiFiXdA1fN3H/3hBhzv7Mcf3yVCfEdK7dciq1nN3akPwMkmjnZGUbOdQAAAABJRU5ErkJggg=="; 
		GenerateImage(str, "e:/test2.png"); 
	} 
} 

原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/tech/pnotes/16336.html

(0)
上一篇 2021年7月19日 19:14
下一篇 2021年7月19日 19:14

相关推荐

发表回复

登录后才能评论