java如何實現(xiàn)圖片轉化為數(shù)據(jù)流
更新時間:2022年01月29日 11:30:12 作者:劍雪風猴
這篇文章主要介紹了java如何實現(xiàn)圖片轉化為數(shù)據(jù)流,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
實現(xiàn)圖片轉化為數(shù)據(jù)流
方法如下
/** * 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")是獲取操作系統(tǒng)緩存的臨時目錄 copyFileFromInputStream(XXXX.class.getResourceAsStream("images/" + image),imageFile); // 系統(tǒng)會讀取XXX.class路徑中images文件夾下的xxx.jpg文件,將其轉換為數(shù)據(jù)流
把圖片轉換成二進制流的代碼
在學習期間,把開發(fā)過程經常用到的一些代碼段做個備份,下邊代碼內容是
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數(shù)據(jù)庫讀取Image類型的數(shù)據(jù)
并轉換成bytes[]或Image圖像文件
{ Image image; MemoryStream mymemorystream = new MemoryStream(mybyte,0, mybyte.Length); image = Image.FromStream(mymemorystream); return image; }
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
Java定時任務Timer、TimerTask與ScheduledThreadPoolExecutor詳解
這篇文章主要介紹了Java定時任務Timer、TimerTask與ScheduledThreadPoolExecutor詳解, 定時任務就是在指定時間執(zhí)行程序,或周期性執(zhí)行計劃任務,Java中實現(xiàn)定時任務的方法有很多,本文從從JDK自帶的一些方法來實現(xiàn)定時任務的需求,需要的朋友可以參考下2024-01-01Mybatis注解方式完成輸入?yún)?shù)為list的SQL語句拼接方式
這篇文章主要介紹了Mybatis注解方式完成輸入?yún)?shù)為list的SQL語句拼接方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-11-11Intellij IDEA基于Springboot的遠程調試(圖文)
這篇文章主要介紹了Intellij IDEA基于Springboot的遠程調試(圖文),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-10-10