2012-02-28 133 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; 
} 

}