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