Proportional scaling of Images Using Java

Source: Internet
Author: User
This article is original. If you need to reprint it, please indicate the author and the source. Thank you!










The basic principle of scaling an image is to create a canvas of the target size, read the source image, and draw the image on the canvas. To make the program generic, the source image and the scaled target image are used separately.
The Code is as follows:


Public
 
Static
 
Void
Scaleimage (inputstream imginputstream,
Outputstream imgoutputstream,
Int
Scale)
{

Try

{

Image SRC
=
Javax. ImageIO. ImageIO. Read (imginputstream );

Int
Width
=
(
Int
) (SRC. getwidth (
Null
)
*
Scale
/
 
100.0
);

Int
Height
=
(
Int
) (SRC. getheight (
Null
)
*
Scale
/
 
100.0
);
Bufferedimage
=
 
New
Bufferedimage (width, height,
Bufferedimage. type_int_rgb );

Bufferedimage. getgraphics (). drawimage (
SRC. getscaledinstance (width, height, image. scale_smooth ),

0
,
0
,
Null
);
Jpegimageencoder Encoder
=
Jpegcodec
. Createjpegencoder (imgoutputstream );
Encoder. encode (bufferedimage );

}

Catch
(Ioexception E)
{
E. printstacktrace ();
}
}


The scale parameter indicates the scale ratio, ranging from 1 to 100. Of course, it can also be greater than 100, that is, to enlarge the image. However, it should be noted that it is too distorted.
Of course, you can also reconstruct the scaleimage method so that it can receive the image file name. The Code is as follows:


Public
 
Static
 
Void
Scaleimage (string imgsrc, string imgdist,
Int
Scale)
{

Try

{
File
=
 
New
File (imgsrc );

If
(
!
File. exists ())
{

Return
;
}
Inputstream is
=
 
New
Fileinputstream (File );
Outputstream OS
=
 
New
Fileoutputstream (imgdist );
Scaleimage (is, OS, scale );
Is. Close ();
OS. Close ();
}

Catch
(Exception E)
{



}
}


The following code scales by 15%

Scaleimage (
"
E: // pictures // test.jpg
"
,
"
E: // test1.jpg
"
,
15
);

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.