java 图片转字符串
package com.baoy.cn;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
public class FileReadTest {
public static boolean download(String imgStr,String imgFile) throws Exception {
if (imgStr == null) // 图像数据为空
return false;
BASE64Decoder decoder = new BASE64Decoder();
try {
// Base64解码
byte[] b = decoder.decodeBuffer(imgStr);
for (int i = 0; i < b.length; ++i) {
if (b[i] < 0) {// 调整异常数据
b[i] += 256;
}
}
// 生成jpeg图片
String imgFilePath = imgFile;// 新生成的图片
OutputStream out = new FileOutputStream(imgFilePath);
out.write(b);
out.flush();
out.close();
return true;
} catch (Exception e) {
throw e;
}
}
public static String upload(String imgFile) throws IOException {
InputStream in = null;
byte[] data = null;
// 读取图片字节数组
try {
in = new FileInputStream(imgFile);
data = new byte[in.available()];
in.read(data);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// 对字节数组Base64编码
BASE64Encoder encoder = new BASE64Encoder();
return encoder.encode(data);
}
@SuppressWarnings("resource")
public static void main(String[] args) throws Exception {
String imgFile = "C:\\Users\\baoy\\Desktop\\1.png"; // 声明File对象
String imgFile2 = "C:\\Users\\baoy\\Desktop\\2.png"; // 声明File对象
String upload = upload(imgFile);
System.out.println(upload);
File file = new File("C:\\Users\\baoy\\Desktop\\1.txt");
FileWriter fileWriter = new FileWriter(file);
fileWriter.write(upload);
fileWriter.flush();
boolean download = download(upload, imgFile2);
System.out.println(download);
}
}
捐助开发者
在兴趣的驱动下,写一个免费
的东西,有欣喜,也还有汗水,希望你喜欢我的作品,同时也能支持一下。 当然,有钱捧个钱场(支持支付宝和微信 以及扣扣群),没钱捧个人场,谢谢各位。
个人主页:http://knight-black-bob.iteye.com/
谢谢您的赞助,我会做的更好!