Java 从文件夹中检索图像,缩小它们的比例,然后将它们保存到另一个文件夹中。怎样(爪哇)

Java 从文件夹中检索图像,缩小它们的比例,然后将它们保存到另一个文件夹中。怎样(爪哇),java,image,Java,Image,我有个小问题。。。文件夹中有数百个图像。它们应该缩小到特定的高度和宽度。所以,问题是。。。从文件夹中检索图像,缩小它们的比例,然后将它们保存到另一个文件夹中。Java有可能吗?如果是,请帮助我,怎么做?这只是为了减少我的应用程序中的内存大小。(所有文件都应为JPEG格式)。您可以使用ImageIO读取图像,然后使用Image.getScaledInstance()方法缩放图像。最后,您可以使用ImageIO写出新图像 哎呀,我不确定使用getScaleInstance()方法时返回的图像类型。I

我有个小问题。。。文件夹中有数百个图像。它们应该缩小到特定的高度和宽度。所以,问题是。。。从文件夹中检索图像,缩小它们的比例,然后将它们保存到另一个文件夹中。Java有可能吗?如果是,请帮助我,怎么做?这只是为了减少我的应用程序中的内存大小。(所有文件都应为JPEG格式)。

您可以使用ImageIO读取图像,然后使用Image.getScaledInstance()方法缩放图像。最后,您可以使用ImageIO写出新图像


哎呀,我不确定使用getScaleInstance()方法时返回的图像类型。ImageIO.write()方法需要RenderImage,因此您可能需要先创建一个BuffereImage,并将缩放后的图像绘制到缓冲区,然后写出BuffereImage。

您可以使用ImageIO读取和处理图像,然后使用ImageGetScaledInstance()方法缩放图像。最后,您可以使用ImageIO写出新图像


哎呀,我不确定使用getScaleInstance()方法时返回的图像类型。ImageIO.write()方法需要渲染图像,因此您可能需要先创建一个BuffereImage并将缩放后的图像绘制到缓冲区,然后写出BuffereImage。

我的解决方案提供了图像,但所有图像都有固定的大小,但我需要它们的特定比例,以适合我的高度和宽度。如果有任何修改,请帮助我

package vimukti.image;

import java.awt.Graphics;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.HeadlessException;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileFilter;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;


public class ImagesScaling {
    File inputDir;
    File outputDir;
    File[] files;


    public ImagesScaling(File srcFile, File destFile) throws Exception{
        inputDir = srcFile;
        outputDir = destFile;

        class JPGFileFilter implements FileFilter {

              public boolean accept(File pathname) {

                if (pathname.getName().endsWith(".jpg"))
                  return true;
                if (pathname.getName().endsWith(".jpeg"))
                  return true;
                return false;
              }
        }
        JPGFileFilter filter = new JPGFileFilter();
        if(!outputDir.exists())
            outputDir.mkdir();

        if(inputDir.isDirectory()){
            files = inputDir.listFiles(filter);
        }
        if(files != null)
            scaling();
    }

    void scaling()throws Exception{
        for(File f : files){
            Image srcImage = ImageIO.read(f);
            Image destImage = srcImage.getScaledInstance(150, 180, Image.SCALE_AREA_AVERAGING);
            BufferedImage buffImg = toBufferedImage(destImage); 

            ImageIO.write(buffImg, "jpg",
                    new File(outputDir.getAbsolutePath() + "\\"+f.getName()));
        }
    }

    void displayFiles(File dir){
        System.out.println("dir: " + dir);
        String[] files = dir.list();
        System.out.println("Files....");
        if(files != null)
            for(String s  : files)
                System.out.println("\t" +dir.getAbsolutePath()+"\\"+ s);
        System.out.println("end");

    }
    public static void main(String[] args)throws Exception {
        ImagesScaling imgScale = new ImagesScaling(
                    new File("C:\\pictures"),
                    new File("C:\\ScaledePictures"));

        imgScale.displayFiles(new File("C:\\ScaledPictures"));
    }
    ////////////////////// Copied ////////////////////////////////////
    // This method returns a buffered image with the contents of an image
    public BufferedImage toBufferedImage(Image image) {
        if (image instanceof BufferedImage) {
            return (BufferedImage)image;
        }

        // This code ensures that all the pixels in the image are loaded
        image = new ImageIcon(image).getImage();

        // Determine if the image has transparent pixels; for this method's
        // implementation, see e661 Determining If an Image Has Transparent Pixels


        // Create a buffered image with a format that's compatible with the screen
        BufferedImage bimage = null;
        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
        try {
            // Determine the type of transparency of the new buffered image
            // Create the buffered image
            GraphicsDevice gs = ge.getDefaultScreenDevice();
            GraphicsConfiguration gc = gs.getDefaultConfiguration();
            bimage = gc.createCompatibleImage(
                image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_RGB);
        } catch (HeadlessException e) {
            // The system does not have a screen
        }

        if (bimage == null) {
            // Create a buffered image using the default color model
            bimage = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_RGB);
        }

        // Copy image to buffered image
        Graphics g = bimage.createGraphics();

        // Paint the image onto the buffered image
        g.drawImage(image, 0, 0, null);
        g.dispose();

        return bimage;
    }
}

添加注释

我的解决方案提供了图像,但所有图像都有固定大小,但我需要它们的大小以适合我的高度和宽度的特定比例。如果有任何修改,请帮助我

package vimukti.image;

import java.awt.Graphics;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.HeadlessException;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileFilter;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;


public class ImagesScaling {
    File inputDir;
    File outputDir;
    File[] files;


    public ImagesScaling(File srcFile, File destFile) throws Exception{
        inputDir = srcFile;
        outputDir = destFile;

        class JPGFileFilter implements FileFilter {

              public boolean accept(File pathname) {

                if (pathname.getName().endsWith(".jpg"))
                  return true;
                if (pathname.getName().endsWith(".jpeg"))
                  return true;
                return false;
              }
        }
        JPGFileFilter filter = new JPGFileFilter();
        if(!outputDir.exists())
            outputDir.mkdir();

        if(inputDir.isDirectory()){
            files = inputDir.listFiles(filter);
        }
        if(files != null)
            scaling();
    }

    void scaling()throws Exception{
        for(File f : files){
            Image srcImage = ImageIO.read(f);
            Image destImage = srcImage.getScaledInstance(150, 180, Image.SCALE_AREA_AVERAGING);
            BufferedImage buffImg = toBufferedImage(destImage); 

            ImageIO.write(buffImg, "jpg",
                    new File(outputDir.getAbsolutePath() + "\\"+f.getName()));
        }
    }

    void displayFiles(File dir){
        System.out.println("dir: " + dir);
        String[] files = dir.list();
        System.out.println("Files....");
        if(files != null)
            for(String s  : files)
                System.out.println("\t" +dir.getAbsolutePath()+"\\"+ s);
        System.out.println("end");

    }
    public static void main(String[] args)throws Exception {
        ImagesScaling imgScale = new ImagesScaling(
                    new File("C:\\pictures"),
                    new File("C:\\ScaledePictures"));

        imgScale.displayFiles(new File("C:\\ScaledPictures"));
    }
    ////////////////////// Copied ////////////////////////////////////
    // This method returns a buffered image with the contents of an image
    public BufferedImage toBufferedImage(Image image) {
        if (image instanceof BufferedImage) {
            return (BufferedImage)image;
        }

        // This code ensures that all the pixels in the image are loaded
        image = new ImageIcon(image).getImage();

        // Determine if the image has transparent pixels; for this method's
        // implementation, see e661 Determining If an Image Has Transparent Pixels


        // Create a buffered image with a format that's compatible with the screen
        BufferedImage bimage = null;
        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
        try {
            // Determine the type of transparency of the new buffered image
            // Create the buffered image
            GraphicsDevice gs = ge.getDefaultScreenDevice();
            GraphicsConfiguration gc = gs.getDefaultConfiguration();
            bimage = gc.createCompatibleImage(
                image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_RGB);
        } catch (HeadlessException e) {
            // The system does not have a screen
        }

        if (bimage == null) {
            // Create a buffered image using the default color model
            bimage = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_RGB);
        }

        // Copy image to buffered image
        Graphics g = bimage.createGraphics();

        // Paint the image onto the buffered image
        g.drawImage(image, 0, 0, null);
        g.dispose();

        return bimage;
    }
}

添加注释

您明确地将图像缩放到150x180,这与您的问题一致,但在这个回答中,您似乎表示希望图像按特定比例缩小。如果这就是您的意思,那么您可以使用一个因子来计算大小,而不是内联常量,例如originalWidth/20。另一方面,请注意扩展可以是任何大小写,因此您可能应该使用“jpg”.equalsIgnoreCase(当然这意味着您必须使用lastIndexOf查找扩展)。祝您好运。作为另一个参考,您可能希望在代码中有“\\”的地方使用File.separator。使用此选项,您无需知道操作系统中斜杠的使用方式。您明确地将图像缩放到150x180-这与您的问题一致,但在这个答案中,您似乎表示希望将图像缩小特定的比例。如果这就是您的意思,那么您可以使用一个因子来计算大小,而不是内联常量,例如originalWidth/20。另一方面,请注意扩展可以是任何大小写,因此您可能应该使用“jpg”.equalsIgnoreCase(当然这意味着您必须使用lastIndexOf查找扩展)。祝您好运。作为另一个参考,您可能希望在代码中有“\\”的地方使用File.separator。使用此选项,您无需知道操作系统中斜杠的方向。请注意,按像素大小缩放JPEG,在“字节减少”方面几乎没有什么好处。通常更有效的方法是保持大小不变并增加JPEG压缩。请注意,按像素大小缩放JPEG,在“字节减少”方面几乎没有什么好处。通常更有效的方法是保持大小不变并增加JPEG压缩。