1

是否可以使用 Scalr实现第一个示例?

我的代码如下:

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);

我想要的是接收这样的图像: 在此处输入图像描述蓝色条是我想用颜色填充的空间。

谢谢

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

4

2 回答 2

2

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

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; 
}
于 2018-05-14T13:07:05.167 回答
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);

这并不理想,但至少它在生成缩略图后处理“宽”图像

于 2013-07-24T11:09:27.723 回答