图像缩放Java

3

我在调整图片大小时遇到了奇怪的问题,但无法确定自己哪里出错了。我已经阅读了很多帖子,它们基本上都使用与我相同的代码:

(我使用Java库Scalr)

File image = new File("myimage.png");
File smallImage = new File("myimage_s");
try {
    BufferedImage bufimage = ImageIO.read(image);

    BufferedImage bISmallImage = Scalr.resize(bufimage, 30); // after this line my dimensions in bISmallImage are correct!
    ImageIO.write(bISmallImage, "png", smallImage); // but my smallImage has the same dimension as the original foto
} catch (Exception e) {}

有人可以告诉我我做错了什么吗?

什么是出现问题的指示?如果您的代码抛出异常catch (Exception e) {}将会让你一头雾水。您是否使用调试器逐步执行代码了? - J0e3gan
http://www.mkyong.com/java/how-to-resize-an-image-in-java/ - Pandiyan Cool
2
我只是删掉了不必要的代码,我的代码中有错误处理等。我没有收到任何异常或其他信息。 "调整大小" 的图像与原始图像的大小相同。 - Markus
为什么要使用特定的库?只需使用Java。 - markspace
Scalr运行正常 - bISmallImage的大小是正确的。只是将BufferedImage转换回File并没有像预期那样工作。(我之前也尝试过使用简单的Java) - Markus
抱歉,我错过了你的评论。我的注意力只集中在空的catch块上。 :} 感谢您后续的评论以澄清。 - J0e3gan
1个回答

3
我认为你的代码没有问题。
我在Eclipse中创建了一个快速测试项目,目标是Java SE 7,并在Windows 7 Pro 64位上使用了imgscalr 4.2
import java.awt.image.BufferedImage;
import java.io.File;

import javax.imageio.ImageIO;

import org.imgscalr.Scalr;

public class ScalrTest {

    public static void main(String[] args) {
        File image = new File("myimage.png");
        File smallImage = new File("myimage_s.png"); // FORNOW: added the file extension just to check the result a bit more easily
        // FORNOW: added print statements just to be doubly sure where we're reading from and writing to
        System.out.println(image.getAbsolutePath());
        System.out.println(smallImage.getAbsolutePath());
        try {
            BufferedImage bufimage = ImageIO.read(image);

            BufferedImage bISmallImage = Scalr.resize(bufimage, 30); // after this line my dimensions in bISmallImage are correct!
            ImageIO.write(bISmallImage, "png", smallImage); // but my smallImage has the same dimension as the original foto
        } catch (Exception e) {
            System.out.println(e.getMessage()); // FORNOW: added just to be sure
        }
    }

}

使用以下 myimage.png...

myimage.png

..., 它生成了以下的myimage_s.png

myimage_s.png

也许有一个环境问题阻碍了你的代码,但是我想到的可能性都会伴随着明确的错误提示。

1
是的,你说得对。我也在另一个应用程序中测试了它。我认为我的问题与Java无关,而是其他方面的问题。感谢你测试我的问题并引导我朝着正确的方向前进! - Markus

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接