Скопируйте изображение в другое место с другим размером

Я пытаюсь скопировать файл изображения из одного места в другое, используя Java. Теперь я хочу сохранить файл изображения для определенного размера, независимо от размера файла изображения в исходном местоположении.

Я использую следующий код, он создает изображение в месте назначения с тем же размером, что и исходный файл:

public class filecopy {
    public static void copyFile(File sourceFile, File destFile)
            throws IOException {
        if (!destFile.exists()) {
            destFile.createNewFile();
        }

        FileChannel source = null;
        FileChannel destination = null;
        try {
            source = new FileInputStream(sourceFile).getChannel();
            destination = new FileOutputStream(destFile).getChannel();

            // previous code: destination.transferFrom(source, 0, source.size());
            // to avoid infinite loops, should be:
            long count = 0;
            long size = source.size();
            while ((count += destination.transferFrom(source, count, size
                    - count)) < size)
                ;
        } finally {
            if (source != null) {
                source.close();
            }
            if (destination != null) {
                destination.close();
            }
        }
    }

    public static void main(String args[]) {
       try {
        File sourceFile = new File("D:/new folder/abc.jpg");
        File destFile = new File("d:/new folder1/abc.jpg");
        copyFile(sourceFile,destFile);
        } catch (IOException ex) {
           ex.printStackTrace();
         }
    }
}

1 ответ

Решение

Вот код для изменения размера изображения согласно вашей спецификации. Внутри метода copyFile,

int width=100,height=75; /* set the width and height here */
BufferedImage inputImage=ImageIO.read(sourceFile);
BufferedImage outputImage=new BufferedImage(width, height,
    BufferedImage.TYPE_INT_RGB);
Graphics2D g=outputImage.createGraphics();
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
    RenderingHints.VALUE_INTERPOLATION_BICUBIC);
g.clearRect(0, 0, width, height);
g.drawImage(inputImage, 0, 0, width, height, null);
g.dispose();
ImageIO.write(outputImage,"jpg",destFile);
/* first parameter is the object of the BufferedImage,
   second parameter is the type of image that you are going to write,
       you can use jpg, bmp, png etc
   third parameter is the destination file object. */
Другие вопросы по тегам