花了一早上的时间总结了下图片的各种转换方式,在此分享下。
import java.io.ByteArrayOutputStream;import java.io.File;import java.util.Base64;import javax.p_w_picpathio.stream.FileImageInputStream;import javax.p_w_picpathio.stream.FileImageOutputStream;public class ccc { public static void main(String[] args) throws Exception{ File file=new File("D://2.png");// File file2=new File("D://3.png"); byte data[]=p_w_picpathTobyte(file);// String str=byteTohex(data);// byte data2[]=hexTobyte(str); byteTop_w_picpath(Base64StringTobyte(byteToBase64String(data)),"d://aaaa.png"); } //图片转二进制 public static byte[] p_w_picpathTobyte(File file)throws Exception{ FileImageInputStream input =new FileImageInputStream(file); ByteArrayOutputStream output = new ByteArrayOutputStream(); byte[] data = null; byte[] buf = new byte[1024]; int numBytesRead = 0; while ((numBytesRead = input.read(buf)) != -1) { output.write(buf, 0, numBytesRead); } data = output.toByteArray(); output.close(); input.close(); return data; } //二进制转字符串 public static String byteTohex(byte[] b)throws Exception{ StringBuffer sb = new StringBuffer(); String stmp = ""; for (int n = 0; n < b.length; n++) { stmp = Integer.toHexString(b[n] & 0XFF); if (stmp.length() == 1) { sb.append("0" + stmp); } else { sb.append(stmp); } } return sb.toString(); } //字符串转二进制 public static byte[] hexTobyte(String str) { if (str == null) return null; str = str.trim(); int len = str.length(); if (len == 0 || len % 2 == 1) return null; byte[] b = new byte[len / 2]; try { for (int i = 0; i < str.length(); i += 2) { b[i / 2] = (byte) Integer.decode("0X" + str.substring(i, i + 2)).intValue(); } return b; } catch (Exception e) { return null; } } //二进制转图片 path为图片地址 public static void byteTop_w_picpath(byte[] data,String path){ if(data.length<3||path.equals("")) return; try{ FileImageOutputStream p_w_picpathOutput = new FileImageOutputStream(new File(path)); p_w_picpathOutput.write(data, 0, data.length); p_w_picpathOutput.close(); System.out.println("Make Picture success,Please find p_w_picpath in " + path); } catch(Exception ex) { System.out.println("Exception: " + ex); ex.printStackTrace(); } } //二进制byte[] 转 base64字符串 public static String byteToBase64String(byte[] data){ String Base64String=Base64.getEncoder().encodeToString(data); return Base64String; } //base64字符串 转 二进制byte[] public static byte[] Base64StringTobyte(String Base64String) { byte[] bytes = Base64.getDecoder().decode(Base64String); return bytes; }
图片转字符串建议使用base64的转换方式,base64字符串传到前台可以直接显示出来。
格式为<img src="data:p_w_picpath/jpg;base64,base64字符串"/>
注:此处的 util.base64包是jdk1.8才有的