我需要从网络中裁剪图像(通过其网址)并返回一个InputStream(可以上传到AWS S3)。我使用org.imgscalr作为库并具有以下方法:
public InputStream cropFile(String url) throws Exception, IOException {
BufferedImage original = ImageIO.read(new URL(url));
BufferedImage target = null;
// resize based on http://www.htmlgoodies.com/beyond/java/create-high-quality-thumbnails-using-the-imgscalr-library.html
target = Scalr.crop(original, 410, 60, 200, 300, Scalr.OP_ANTIALIAS);
InputStream is = (InputStream) ImageIO.createImageInputStream(target);
Assert.assertNotNull(is);// it always returns null!!!
return is;
}
我用以下方法调用该方法:
InputStream is = cropFile("http://fengyuanchen.github.io/cropperjs/img/picture.jpg");
然后尝试将其上传到AWS S3:
PutObjectRequest request = new PutObjectRequest(AWSConfig.getBucket(), key, is, meta);
s3.putObject(request);
不幸的是,我不断获得一个空输入流(在上面的断言点)。如果我将createImage更改为:
ImageIO.write(target, "jpg", new File("c:\\dest.jpg"));
然后写入正确的图像(因此它可以工作)。