时间:2023-02-18 10:16:49 | 栏目:JAVA代码 | 点击:次
/** * 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文件,将其转换为数据流
在学习期间,把开发过程经常用到的一些代码段做个备份,下边代码内容是
应该能对各朋友也有用处
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; }
并转换成bytes[]或Image图像文件
{ Image image; MemoryStream mymemorystream = new MemoryStream(mybyte,0, mybyte.Length); image = Image.FromStream(mymemorystream); return image; }