图片和字符串相互转化
功能的实现应用到了java io
以下是代码实现:
package myProject; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.util.Base64; import java.util.Base64.Decoder; import java.util.Base64.Encoder; public class ImageString { public static void main(String[] args){ File file =new File("D:\\1.jpg"); File file_new=new File("D:\\images\\2.jpg"); try{ //读图片文件(图片转化成字符串) FileInputStream fileInputStream=new FileInputStream(file); BufferedInputStream bufferedInputStream=new BufferedInputStream(fileInputStream); byte[] b=new byte[bufferedInputStream.available()]; bufferedInputStream.read(b); bufferedInputStream.close(); fileInputStream.close(); // 对字节数组Base64编码 Encoder encoder=Base64.getEncoder(); // BASE64Encoder encoder = new BASE64Encoder(); // 返回Base64编码过的字节数组字符串 // String str=encoder.encode(b); String str=encoder.encodeToString(b); System.out.println(str); //字符串转化成图片 //将读的内容写入新的文件 if(!file_new.exists()){ file_new.createNewFile(); } FileOutputStream fileOutputStream=new FileOutputStream(file_new); BufferedOutputStream bufferedOutputStream=new BufferedOutputStream(fileOutputStream); //解码 //BASE64Decoder decoder = new BASE64Decoder(); //byte[] b2=decoder.decodeBuffer(str); Decoder decoder=Base64.getDecoder(); byte[] b2=decoder.decode(str); bufferedOutputStream.write(b2); bufferedOutputStream.flush(); bufferedOutputStream.close(); fileOutputStream.close(); }catch(Exception e){ e.printStackTrace(); } } }
这里用到了BASE64编码解码