无法为大图像文件创建缩略图

时间:2011-04-24 23:00:17

标签: java image graphics jpeg

我是图形的新手。我一直在使用这段代码来制作图像文件的缩略图。当我使用像墙纸一样的小文件(~100KB)时,它工作正常但是当我使用大小约为5MB的图像文件(照片)时,它只产生几个字节(~1-8KB)的文件,显示为黑色图像。我给它的宽度和高度并不重要。这可能会出错?图像类型或产生图像的相机之间有区别吗?我确定问题图像来自不同的相机而不是没有问题的相机。我提供高质量的参数作为100,不会错过任何细节......

        ByteArrayOutputStream out = new ByteArrayOutputStream();
    try {
        int dx = thumbWidth, dy = thumbHeight; 

        Image image = Toolkit.getDefaultToolkit().createImage(file);
        MediaTracker mediaTracker = new MediaTracker(new Container());
        mediaTracker.addImage(image, 0);
        mediaTracker.waitForID(0);

        double thumbRatio = (double)thumbWidth / (double)thumbHeight;

        int imageWidth = image.getWidth(null);
        int imageHeight = image.getHeight(null);
        double imageRatio = (double)imageWidth / (double)imageHeight;

        if (thumbRatio < imageRatio) {
          thumbHeight = (int)(thumbWidth / imageRatio);
        } else {
          thumbWidth = (int)(thumbHeight * imageRatio);
        }

        if(thumbWidth > dx) {
            thumbWidth = dx;
            thumbHeight = (int)(thumbWidth / imageRatio);
        }
        if(thumbHeight > dy)
        {
            thumbHeight = dy;
            thumbWidth = (int) (thumbHeight*imageRatio);
        }

        log.debug("X="+thumbWidth+" Y="+thumbHeight);

        BufferedImage thumbImage = new BufferedImage(thumbWidth, thumbHeight, BufferedImage.TYPE_INT_RGB);
        Graphics2D graphics2D = thumbImage.createGraphics();
        graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
        graphics2D.drawImage(image, 0, 0, thumbWidth, thumbHeight, null);

        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
        JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(thumbImage);

        quality = Math.max(0, Math.min(quality, 100));
        param.setQuality((float)quality / 100.0f, false);

        encoder.setJPEGEncodeParam(param);
        encoder.encode(thumbImage);
        log.debug("ThumbLength"+out.toByteArray().length);

        FileOutputStream fos = new FileOutputStream("/root/testx.jpg");
        fos.write(out.toByteArray());
        fos.close();

    } catch(Exception e) { log.debug(e.getMessage());}

    return out.toByteArray(); 

1 个答案:

答案 0 :(得分:2)

您可以尝试BufferedImage.TYPE_INT_ARGB,如图here所示。

此外,您的MediaTracker正在等待同一个帖子; ImageIO.read()可能更简单。

附录:另请考虑AffineTransformOp,但srcdst必须不同。