Image,File与Byte转换

来源:互联网 发布:当代著名网络小说家 编辑:程序博客网 时间:2024/05/16 04:42

原址:http://superheizai.iteye.com/blog/630855
从byte[]转Image 
public static byte[] getImageBytes(Image image) throws Exception {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageLoader imageLoader = new ImageLoader();
imageLoader.data = new ImageData[] { image.getImageData() };
imageLoader.save(baos, image.type);
byte[] imageByteArray = baos.toByteArray();
try {
baos.close();
} catch (Exception e) {
e.printStackTrace();
}
return imageByteArray;
}
从File转byte[] 
public static byte[] getBytesFromFile(File f){
if (f == null){
return null;
}
try {
FileInputStream stream = new FileInputStream(f);
ByteArrayOutputStream out = new ByteArrayOutputStream(1000);
byte[] b = new byte[1000];
int n;
while ((n = stream.read(b)) != -1)
out.write(b, 0, n);
stream.close();
out.close();
return out.toByteArray();
} catch (IOException e){
}
return null;
}
从byte[]转file 
public static File getFileFromBytes(byte[] b, String outputFile) ...{
BufferedOutputStream stream = null;
File file = null;
try ...{
file = new File(outputFile);
FileOutputStream fstream = new FileOutputStream(file);
stream = new BufferedOutputStream(fstream);
stream.write(b);
} catch (Exception e) ...{
e.printStackTrace();
} finally ...{
if (stream != null) ...{
try ...{
stream.close();
} catch (IOException e1) ...{
e1.printStackTrace();
}
}
}
return file;
}



原创粉丝点击