java如何实现图片转化为数据流

 更新时间:2022年1月29日 20:23  点击:282 作者:剑雪风猴

实现图片转化为数据流

方法如下

/**
	 * 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 File(System.getProperty("java.io.tmpdir"), image); //System.getProperty("java.io.tmpdir")是获取操作系统缓存的临时目录
copyFileFromInputStream(XXXX.class.getResourceAsStream("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;
}

以上为个人经验,希望能给大家一个参考,也希望大家多多支持猪先飞。

原文出处:https://blog.csdn.net/weixin_47534665/article/details/107466

[!--infotagslink--]

相关文章