java中圖像與數組轉換


import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class ImageWithArray {
 public static void main(String[] args) {
  // 讀取圖片到BufferedImage
  BufferedImage bf = readImage("c:\\tmp\\6\\female.png");//這里寫你要讀取的絕對路徑+文件名
  // 將圖片轉換為二維數組
  int[][] rgbArray1 = convertImageToArray(bf);
  // 輸出圖片到指定文件
  writeImageFromArray("c:\\tmp\\2.png", "png", rgbArray1);//這里寫你要輸出的絕對路徑+文件名
  System.out.println("圖片輸出完畢!");
 }
 public static BufferedImage readImage(String imageFile){
  File file = new File(imageFile);
  BufferedImage bf = null;
  try {
   bf = ImageIO.read(file);
  } catch (IOException e) {
   e.printStackTrace();
  }
  return bf;
 }
 public static int[][] convertImageToArray(BufferedImage bf) {
  // 獲取圖片寬度和高度
  int width = bf.getWidth();
  int height = bf.getHeight();
  // 將圖片sRGB數據寫入一維數組
  int[] data = new int[width*height];
  bf.getRGB(0, 0, width, height, data, 0, width);
  // 將一維數組轉換為為二維數組
  int[][] rgbArray = new int[height][width];
  for(int i = 0; i < height; i++)
   for(int j = 0; j < width; j++)
    rgbArray[i][j] = data[i*width + j];
  return rgbArray;
 }
 public static void writeImageFromArray(String imageFile, String type, int[][] rgbArray){
  // 獲取數組寬度和高度
  int width = rgbArray[0].length;
  int height = rgbArray.length;
  // 將二維數組轉換為一維數組
  int[] data = new int[width*height];
  for(int i = 0; i < height; i++)
   for(int j = 0; j < width; j++)
    data[i*width + j] = rgbArray[i][j];
  // 將數據寫入BufferedImage
  BufferedImage bf = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);
  bf.setRGB(0, 0, width, height, data, 0, width);
  // 輸出圖片
  try {
   File file= new File(imageFile);
   ImageIO.write((RenderedImage)bf, type, file);
  } catch (IOException e) {
   e.printStackTrace();
  }
 }
}

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM