生成缩略图并用颜色填充空白区域

时间:2013-07-21 13:55:50

标签: java image-processing thumbnails scalr

是否可以使用Scalr实现first example

我的代码如下:

BufferedImage thumbnail = Scalr.resize(ImageIO.read(sourceFile), Scalr.Method.ULTRA_QUALITY, Scalr.Mode.FIT_TO_WIDTH,
                width, height, Scalr.OP_ANTIALIAS);
ImageIO.write(thumbnail, destinationfile.getExtension(), destinationfile);

我想要的是接收这样的图像: enter image description here其中蓝色条是我想用颜色填充的空间。

谢谢

更新:也许可以使用Thumbnailator实现?

2 个答案:

答案 0 :(得分:1)

没人知道所以我会发布我的解决方案...... 我决定继续使用Scalr(我没有检查过Thumbnailator的最后一个版本,但之前的版本在大图片上失败了)。 首先,我调用resize方法,然后,如果新缩略图的大小比较大,那么我会调用crop方法按中心裁剪缩略图。代码如下:

BufferedImage thumbnail = Scalr.resize(sourceFile, Scalr.Method.ULTRA_QUALITY, Scalr.Mode.AUTOMATIC, destinationSize.width, destinationSize.height);
if (thumbnail.getWidth() > destinationSize.width)
    thumbnail = Scalr.crop(thumbnail, (thumbnail.getWidth() - destinationSize.width) / 2, 0, destinationSize.width, destinationSize.height);
else if (thumbnail.getHeight() > destinationSize.height) 
    thumbnail = Scalr.crop(thumbnail, 0, (thumbnail.getHeight() - destinationSize.height) / 2, destinationSize.width, destinationSize.height);

这不是理想的,但至少它会在生成缩略图后处理“广泛”的图像

答案 1 :(得分:1)

刚刚完成!也许它可以帮到你!

public static BufferedImage resizeAndCrop(BufferedImage bufferedImage) throws IOException {

        int himg = bufferedImage.getHeight();
        int wimg = bufferedImage.getWidth();

        double rateh = himg/dim;
        double ratew = wimg/dim;
        double rate = ratew;
        if(rateh>ratew)
        rate = rateh;

        int dimhimg = (int) (himg/rate);
        int dimwimg = (int) (wimg/rate);

        double startw = dim/2 - dimwimg/2;
        double starth = dim/2 - dimhimg/2;

        BufferedImage tThumbImage = new BufferedImage( dim, dim, BufferedImage.TYPE_INT_RGB );
        Graphics2D tGraphics2D = tThumbImage.createGraphics(); //create a graphics object to paint to
        tGraphics2D.setBackground( Color.WHITE );
        tGraphics2D.setPaint( Color.WHITE );
        tGraphics2D.fillRect( 0, 0, dim, dim );
        tGraphics2D.setRenderingHint( RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        tGraphics2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING,  RenderingHints.VALUE_ANTIALIAS_ON);
        tGraphics2D.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING,  RenderingHints.VALUE_COLOR_RENDER_QUALITY); 
        tGraphics2D.drawImage( bufferedImage, (int)startw, (int)starth, dimwimg, dimhimg, null ); //draw the image scaled

        File ff = new File(path + "jdata/tmp/prova.jpg");
        ImageIO.write( tThumbImage, "JPG", ff); //write the image to a file
        BufferedImage croppedContainMethod = ImageIO.read(ff);
        return croppedContainMethod; 

}