2012-02-28 184 views
-1

我有一個包含300個圖像文件名的數組,並希望將每個文件名轉換爲新的BufferedImage。Java - 將文件[]項目轉換爲BufferedImage

陣300個的圖片名稱是由此產生:

//Default image directory (to convert to greyscale). 
static File dir = new File("images"); 
//Array of original image filenames. 
static File imgList[] = dir.listFiles(); 

public static void processGreyscale(){ 
    if(dir.isDirectory()){ 
     for(File img : imgList){ 
      if(img.isFile()){ 
       //functions are carried out here. 
      } 
      else{ 
       //functions are carried out here. 
      } 
     } 
    } 
} 

有沒有辦法使用的東西線沿線的所​​有imgList[x]項轉換爲BufferedImage項目:

File file = new File(new BufferedImage(imgList[0-300])); 

try { 
    image = ImageIO.read(file); 
} catch (IOException e) { 
    ... 
} 
+1

代碼的第2位沒有意義,且不會編譯。在File的數組上循環,用ImageIO加載每一個 - 每個加載都會返回一個Image ...請參閱[Java Tutorial](http://docs.oracle.com/javase/tutorial/2d/images/loadimage.html )在這。 – DNA 2012-02-28 23:44:35

+0

第二部分不會編譯,因爲它是我希望它看起來的一段理論代碼。 – MusTheDataGuy 2012-02-29 12:15:04

回答

1

我希望下面的解決方案會幫助你。

import java.awt.Graphics2D; 
import java.awt.Image; 
import java.awt.image.BufferedImage; 
import java.awt.image.ImageObserver; 
public class BufferedImageBuilder { 

private static final int DEFAULT_IMAGE_TYPE = BufferedImage.TYPE_INT_RGB; 

public BufferedImage bufferImage(Image image) { 
    return bufferImage(image, DEFAULT_IMAGE_TYPE); 
} 

public BufferedImage bufferImage(Image image, int type) { 
    BufferedImage bufferedImage = new BufferedImage(image.getWidth(null), image.getHeight(null), type); 
    Graphics2D g = bufferedImage.createGraphics(); 
    g.drawImage(image, null, null); 
    waitForImage(bufferedImage); 
    return bufferedImage; 
} 

private void waitForImage(BufferedImage bufferedImage) { 
    final ImageLoadStatus imageLoadStatus = new ImageLoadStatus(); 
    bufferedImage.getHeight(new ImageObserver() { 
     public boolean imageUpdate(Image img, int infoflags, int x, int y, int width, int height) { 
      if (infoflags == ALLBITS) { 
       imageLoadStatus.heightDone = true; 
       return true; 
      } 
      return false; 
     } 
    }); 
    bufferedImage.getWidth(new ImageObserver() { 
     public boolean imageUpdate(Image img, int infoflags, int x, int y, int width, int height) { 
      if (infoflags == ALLBITS) { 
       imageLoadStatus.widthDone = true; 
       return true; 
      } 
      return false; 
     } 
    }); 
    while (!imageLoadStatus.widthDone && !imageLoadStatus.heightDone) { 
     try { 
      Thread.sleep(300); 
     } catch (InterruptedException e) { 

     } 
    } 
} 

class ImageLoadStatus { 

    public boolean widthDone = false; 
    public boolean heightDone = false; 
} 

}