簡體   English   中英

Java-為新的BufferedImage文件生成新的文件名

[英]Java - Generate New Filename for New BufferedImage Files

是否可以為使用以下代碼處理的每個圖像生成一個新的圖像名稱(我已在相關部分中進行了突出顯示)?

public static void makeBinary(File image) { 
try{
    //Read in original image. 
    BufferedImage inputImg = ImageIO.read(image);

    //Obtain width and height of image.
    double image_width = inputImg.getWidth();
    double image_height = inputImg.getHeight();

    //New images to draw to.
    BufferedImage bimg = null;
    BufferedImage img = inputImg;

    //Draw the new image.      
    bimg = new BufferedImage((int)image_width, (int)image_height, BufferedImage.TYPE_BYTE_BINARY);
    Graphics2D gg = bimg.createGraphics();
    gg.drawImage(img, 0, 0, img.getWidth(null), img.getHeight(null), null);


// ************* THIS IS WHERE I AM HAVING DIFFICULTY ***************

    //Save new binary (output) image.   
    String temp = "_inverted";
    File fi = new File("images\\" + temp + ".jpg");
    ImageIO.write(bimg, "jpg", fi);

// ******************************************************************


}
 catch (Exception e){
    System.out.println(e);
 }
}

我有300張圖像,編號為001.jpg - 300.jpg ,我想要的是將每個新輸出的圖像命名為binary_001.jpg - binary_300.jpg

調用makeBinary()方法位於另一個類中,該方法是:

public static void listFiles() {

    File dir = new File("images");
    File imgList[] = dir.listFiles();

    if(dir.isDirectory()){
        for(File img : imgList){
            if(img.isFile()){
                MakeBinary.makeBinary(img);
                System.out.println(img + ": processed successfully.");
            }
            else{
                System.out.println("Directory detected; skipping to next file,");
            }
        }
    }
}

我該如何實現呢?

非常感謝。

從您的File image參數獲取文件名,並將其添加到新文件名:

String temp = image.getName() + "_inverted";
File fi = new File("images\\" + temp + ".jpg");
ImageIO.write(bimg, "jpg", fi);

您可以只連接原始圖像的名稱(在您的代碼“圖像”中使用字符串“ _inverted”傳遞給ImageIO,這樣,您將為處理的每個圖像都具有原始名稱:image.jpg-> image_inverted.jpg

File fi = new File("images\\" + "binary_" + image.getName());

應該做到的。

甚至更好:

File fi = new File(image.getParent(), "binary_" + image.getName());

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM