Resizing an image in swing

前端 未结 4 1231
名媛妹妹
名媛妹妹 2021-01-06 02:46

I have snippet of code that I am using for the purpose of resizing an image to a curtain size (I want to change the resolution to something like 200 dpi). Basically the reas

4条回答
  •  独厮守ぢ
    2021-01-06 03:19

    You don't really have to care about the details of scaling images. The Image class has already a method getScaledInstance(int width, int height, int hints) designed for this purpose. Java documentation says:

    Creates a scaled version of this image. A new Image object is returned which will render the image at the specified width and height by default. The new Image object may be loaded asynchronously even if the original source image has already been loaded completely. If either the width or height is a negative number then a value is substituted to maintain the aspect ratio of the original image dimensions.

    And you can use it like this:

    // Scale Down the original image fast
    Image scaledImage = imageToScale.getScaledInstance(newWidth, newHighth, Image.SCALE_FAST);
    // Repaint this component
    repaint();
    

    Check this for a complete example.

提交回复
热议问题