實際實作圖片的包括 BufferedImage 和 VolatileImage。
一般要把圖片讀取到記憶體中,或者是要把記憶體中的圖片寫入到檔案,都可以透過 ImageIO 來進行。
以下是讀取圖片,並且將圖片轉成 byte 陣列的方法(參考 [1-2]):
1 2 3 4 5 6 7 8 |
File originalImgFile = new File( "D:\\0.jpg" ); BufferedImage bufferedImage = ImageIO.read(originalImgFile); // convert BufferedImage to byte array ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write(bufferedImage, "jpg" , baos); baos.flush(); byte [] originalImgByte = baos.toByteArray(); baos.close(); |
將圖片寫入成檔案時的方法(參考 [2],其實就是把 byte 陣列寫成檔案而已 XD):
1 2 3 4 5 6 7 8 |
// Get the byte array of the image. byte [] resizedBytes = baos.toByteArray(); // Construct the file. File resizedImgFile = new File( "resize_small.jpg" ); // Write the image bytes to file. FileOutputStream fos = new FileOutputStream(resizedImgFile); fos.write(resizedBytes); fos.close(); |
參考資料:
1、[Java] 取得Image的byte[]
2、How To Convert Byte[] To BufferedImage In Java
沒有留言:
張貼留言