java读取 png,如何让java的ImageBuffer正确读取PNG文件?

在Windows上运行正常的Java代码,在Linux环境下处理PNG文件时遇到错误,类型被识别为0。问题在于Linux版本的Java存在bug。解决方案是检查图像类型,如果为0,则手动设置为5,这能解决Linux上的问题,但可能不适用于所有情况。此方法在常见图像类型上工作良好,目前未引发其他问题。
摘要由CSDN通过智能技术生成

For some reason, opening up some PNG files using ImageBuffer and ImageIO does not work. Here's some code I am using that works fine for resizing/cropping JPGs:

BufferedImage image = ImageIO.read(new File(location));

BufferedImage croppedImage = image.getSubimage(

cropInfo.getX(), cropInfo.getY(), cropInfo.getW(), cropInfo.getH());

BufferedImage resizedImage = new BufferedImage(

TARGET_WIDTH, TARGET_HEIGHT, croppedImage.getType());

Graphics2D g = resizedImage.createGraphics();

g.drawImage(croppedImage, 0, 0, TARGET_WIDTH, TARGET_HEIGHT, null);

g.dispose();

this.changeContentType("image/png", ".png"); // not really relevant. just a property

ImageIO.write(resizedImage, "png", new File(location));

return resizedImage;

The goal of this function is to take whatever type is given, resize and crop the image, and then save it to PNG with the same filename.

It works on Windows, but if I crop/resize on Linux (lenny), it crashes altogether and complains about the type of the file (it says the type is 0).

java.lang.IllegalArgumentException: Unknown image type 0

java.awt.image.BufferedImage.(BufferedImage.java:490)

trainingdividend.domain.file.ServerImage.resizeImage(ServerImage.java:68)

trainingdividend.domain.file.ServerImage.cropAndResize(ServerImage.java:80)

trainingdividend.service.user.UserAccountManagerImpl.cropAvatar(UserAccountManagerImpl.java:155)

sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)

sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)

sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)

Solutions?

Is there another library I can use altogether?

解决方案

When running my function on Windows, croppedImaged.getType() returns the value 5. So, the simple "hack" is to store the type, check to see if it's 0... and if it is, set the value to 5 manually.

int imageType = croppedImage.getType();

if(imageType == 0) imageType = 5;

We then pass in imageType instead and it should work on Linux.

I am sure this has the drawback that if the value is 0 in other cases, it will set it to 5 and that will be wrong. However, this seems to work for common image types on Linux and it hasn't caused any problems.

It's pretty clear that the Windows version of Java 1.6 is perfectly fine, but the Linux version has a bug in it.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值