java如何实现图⽚转化为数据流
⽬录
实现图⽚转化为数据流
⽅法如下
使⽤⽅法如下
把图⽚转换成⼆进制流的代码
java中如何把图⽚转换成⼆进制流的代码
从SQLServer数据库读取Image类型的数据
实现图⽚转化为数据流
⽅法如下
java连接sqlserver数据库
/**
* Copy file from inputStream
*
* @param is
* @param f2
* @throws Exception
*/
public static void copyFileFromInputStream( InputStream is, File f2 ) throws Exception {
int length = 2097152;
FileOutputStream out = new FileOutputStream( f2 );
byte[] buffer = new byte[length];
while (true) {
int ins = is.read( buffer );
if ( ins == -1 ) {
is.close( );
out.flush( );
out.close( );
break;
}
out.write( buffer , 0 , ins );
}
}
使⽤⽅法如下
String image =  "XXX.jpg";
File imageFile= new Property("pdir"), image); //Property("pdir")是获取操作系统缓存的临时⽬录copyFileFromInputStream(ResourceAsStream("images/" + image),imageFile);
// 系统会读取XXX.class路径中images⽂件夹下的xxx.jpg⽂件,将其转换为数据流
把图⽚转换成⼆进制流的代码
在学习期间,把开发过程经常⽤到的⼀些代码段做个备份,下边代码内容是
java中如何把图⽚转换成⼆进制流的代码
应该能对各朋友也有⽤处
public byte[] SetImageToByteArray(string fileName)
{ FileStream fs = new FileStream(fileName, FileMode.Open);
int streamLength = (int)fs.Length; byte[] image = new byte[streamLength];
fs.Read(image, 0, streamLength);
fs.Close();
return image; }
public byte[]
SetImageToByteArray(FileUpload FileUpload1)
{ Stream stream = FileUpload1.PostedFile.InputStream;
byte[] photo = new byte[FileUpload1.PostedFile.ContentLength];
stream.Read(photo, 0, FileUpload1.PostedFile.ContentLength);
stream.Close();
return photo;
}
从SQLServer数据库读取Image类型的数据
并转换成bytes[]或Image图像⽂件
{ Image image; MemoryStream mymemorystream = new MemoryStream(mybyte,0, mybyte.Length);image = Image.FromStream(mymemorystream);
return image;
}
以上为个⼈经验,希望能给⼤家⼀个参考,也希望⼤家多多⽀持。