Simple Java Image processing class (Image watermark image scaling) _java

Source: Internet
Author: User

Copy Code code as follows:



Import Java.awt.AlphaComposite;


Import Java.awt.Color;


Import Java.awt.Font;


Import Java.awt.Graphics;


Import Java.awt.Graphics2D;


Import Java.awt.Image;


Import Java.awt.Toolkit;


Import Java.awt.color.ColorSpace;


Import Java.awt.geom.AffineTransform;


Import java.awt.image.AffineTransformOp;


Import Java.awt.image.BufferedImage;


Import java.awt.image.ColorConvertOp;


Import Java.awt.image.CropImageFilter;


Import Java.awt.image.FilteredImageSource;


Import Java.awt.image.ImageFilter;


Import Java.io.File;


Import java.io.IOException;

Import Javax.imageio.ImageIO;

/**
* Picture processing Tool class:<br>
* Function: Zoom image, cut image, image type conversion, color turn black and white, text watermark, image watermark, etc.
* @author Administrator
*/
public class Imageutils {

   /**
     * Several common picture formats
     */
     public static string image_type_gif = "GIF";//Graphics Interchange Format
    public static string image_type_jpg = " JPG//Joint photo Expert Group
    public static String image_type_jpeg = "JPEG";//Joint Photographic expert Group
    public static String image_type_bmp = "BMP" or shorthand for the English bitmap (bitmap), which is the standard image file format in the Windows operating system
    public static string image_type_png = "PNG";/Portable Network Graphics
    public static string image_type_psd = "PSD";//Photo Shop's special format Photoshop

   /**
     * Program entry: For testing
     * @param args
     */
    public static void Main (string[] args) {
        //1-Zoom Image:
       //Method One: Scaling by scale
         Imageutils.scale ("E:/abc.jpg", "E:/abc_scale.jpg", 2, true);//test OK
        /Method Two: Scale by height and width
        imageutils.scale2 ("E :/abc.jpg "," e:/abc_scale2.jpg ", +, true);/test OK

2-Cut Image:
Method One: According to the specified starting point coordinates and wide-height cutting
Imageutils.cut ("E:/abc.jpg", "E:/abc_cut.jpg", 0, 0, 400, 400);//test OK
Method Two: Specify the number of rows and columns for the slice
Imageutils.cut2 ("E:/abc.jpg", "e:/", 2, 2);//test OK
Method Three: Specify the width and height of the slice
IMAGEUTILS.CUT3 ("E:/abc.jpg", "e:/", 300, 300);//test OK

Image type conversion:
Imageutils.convert ("E:/abc.jpg", "GIF", "e:/abc_convert.gif");//test OK

4-color Turn black and white:
Imageutils.gray ("E:/abc.jpg", "e:/abc_gray.jpg");//test OK

5-Add a text watermark to the picture:
Method One:
Imageutils.presstext ("I am watermark text", "E:/abc.jpg", "e:/abc_presstext.jpg", "XXFarEastFont-Arial", font.bold,color.white,80, 0, 0, 0.5f); Test OK
Method Two:
IMAGEUTILS.PRESSTEXT2 ("I also watermark text", "E:/abc.jpg", "e:/abc_presstext2.jpg", "blackbody", "Color.White", "0, 0, 0.5f");//test OK

6-Add a picture watermark to the picture:
Imageutils.pressimage ("E:/abc2.jpg", "e:/abc.jpg", "E:/abc_pressimage.jpg", 0, 0, 0.5f);//test OK
}

/**


* Zoom image (scaled proportionally)


* @param srcimagefile source image file Address


* @param result scaled image address


* @param scale scaling ratio


* @param flag Zoom selection: true amplification; False narrowing;


*/


Public final static void scale (string srcimagefile, string result,


int scale, Boolean flag) {


try {


BufferedImage src = imageio.read (new File (Srcimagefile)); Read into file


int width = src.getwidth (); Get Source image width


int height = src.getheight (); Get source Diagram length


if (flag) {//Zoom in


width = width * scale;


Height = height * scale;


else {//Zoom Out


width = Width/scale;


Height = Height/scale;


}


Image image = Src.getscaledinstance (width, height,


Image.scale_default);


BufferedImage tag = new BufferedImage (width, height,


BUFFEREDIMAGE.TYPE_INT_RGB);


Graphics g = tag.getgraphics ();


G.drawimage (image, 0, 0, NULL); Draw a smaller figure


G.dispose ();


Imageio.write (Tag, "JPEG", new file (result));//output to file stream


catch (IOException e) {


E.printstacktrace ();


}


}

/**


* Zoom image (zoom by height and width)


* @param srcimagefile source image file Address


* @param result scaled image address


* @param height after height scaling


* Width of the scale after @param width


* @param BB ratio is not the need for filler: true for filler; False is not filler;


*/


Public final static void Scale2 (string srcimagefile, string result, int height, int width, Boolean bb) {


try {


Double ratio = 0.0; Scaling ratio


File F = new file (srcimagefile);


BufferedImage bi = imageio.read (f);


Image itemp = bi.getscaledinstance (width, height, bi.) Scale_smooth);


Calculation ratio


if (Bi.getheight () &gt; height) | | (Bi.getwidth () &gt; width)) {


if (Bi.getheight () &gt; Bi.getwidth ()) {


Ratio = (new Integer (height)). Doublevalue ()


/Bi.getheight ();


} else {


Ratio = (new Integer (width)). Doublevalue ()/bi.getwidth ();


}


Affinetransformop op = new Affinetransformop (affinetransform


. getscaleinstance (ratio, ratio), null);


itemp = op.filter (bi, NULL);


}


if (BB) {//Filler


BufferedImage image = new BufferedImage (width, height,


BUFFEREDIMAGE.TYPE_INT_RGB);


Graphics2D g = image.creategraphics ();


G.setcolor (Color.White);


G.fillrect (0, 0, width, height);


if (width = = itemp.getwidth (null))


G.drawimage (itemp, 0, (Height-itemp.getheight (NULL))/2,


Itemp.getwidth (NULL), itemp.getheight (null),


Color.White, NULL);


Else


G.drawimage (Itemp, (Width-itemp.getwidth (NULL))/2, 0,


Itemp.getwidth (NULL), itemp.getheight (null),


Color.White, NULL);


G.dispose ();


itemp = image;


}


Imageio.write ((bufferedimage) itemp, "JPEG", new File (result));


catch (IOException e) {


E.printstacktrace ();


}


}





/**


* Image cutting (according to the specified starting point coordinates and wide-high cutting)


* @param srcimagefile Source image Address


* @param the image address after result slicing


* @param x Target slice start coordinates x


* @param y target slice start coordinates y


* @param width of the target slice


* @param height of target slice


*/


Public final static void cut (String srcimagefile, string result,


int x, int y, int width, int height) {


try {


Reading source Images


BufferedImage bi = imageio.read (new File (Srcimagefile));


int srcwidth = Bi.getheight (); Source Chart Width


int srcheight = Bi.getwidth (); Source Diagram Height


if (srcwidth &gt; 0 &amp;&amp; srcheight &gt; 0) {


Image image = Bi.getscaledinstance (Srcwidth, Srcheight,


Image.scale_default);


The four parameters are image starting coordinates and width-height respectively.


That is: cropimagefilter (int x,int y,int width,int height)


ImageFilter cropfilter = new CropImageFilter (x, y, width, height);


Image img = Toolkit.getdefaulttoolkit (). CreateImage (


New FilteredImageSource (Image.getsource (),


Cropfilter));


BufferedImage tag = new BufferedImage (width, height, bufferedimage.type_int_rgb);


Graphics g = tag.getgraphics ();


G.drawimage (IMG, 0, 0, width, height, null); Draw the cut figure after


G.dispose ();


Output as File


Imageio.write (Tag, "JPEG", new File (result));


}


catch (Exception e) {


E.printstacktrace ();


}


}





/**


* Image Cutting (Specify the number of rows and columns of the slice)


* @param srcimagefile Source image Address


* @param descdir Slice destination Folder


* @param row number of rows target slices. Default 2, must be within range [1, 20]


* @param cols The number of target slice columns. Default 2, must be within range [1, 20]


*/


Public final static void Cut2 (String srcimagefile, String Descdir,


int rows, int cols) {


try {


if (rows&lt;=0| | ROWS&GT;20) rows = 2; Slices of rows


if (cols&lt;=0| | COLS&GT;20) cols = 2; Number of slice columns


Reading source Images


BufferedImage bi = imageio.read (new File (Srcimagefile));


int srcwidth = Bi.getheight (); Source Chart Width


int srcheight = Bi.getwidth (); Source Diagram Height


if (srcwidth &gt; 0 &amp;&amp; srcheight &gt; 0) {


Image img;


ImageFilter Cropfilter;


Image image = Bi.getscaledinstance (Srcwidth, Srcheight, Image.scale_default);


int destwidth = Srcwidth; width of each slice


int destheight = Srcheight; The height of each slice


Calculate the width and height of slices


if (srcwidth% cols = = 0) {


Destwidth = Srcwidth/cols;


} else {


Destwidth = (int) Math.floor (srcwidth/cols) + 1;


}


if (srcheight% rows = = 0) {


Destheight = srcheight/rows;


} else {


Destheight = (int) Math.floor (srcwidth/rows) + 1;


}


Looping to create slices


Improved idea: Whether multithreading can speed up the cutting speed


for (int i = 0; i &lt; rows; i++) {


for (int j = 0; J &lt; cols; J + +) {


The four parameters are image starting coordinates and width-height respectively.


That is: cropimagefilter (int x,int y,int width,int height)


Cropfilter = new CropImageFilter (J * destwidth, I * destheight,


Destwidth, Destheight);


img = Toolkit.getdefaulttoolkit (). CreateImage (


New FilteredImageSource (Image.getsource (),


Cropfilter));


BufferedImage tag = new BufferedImage (Destwidth,


Destheight, Bufferedimage.type_int_rgb);


Graphics g = tag.getgraphics ();


G.drawimage (IMG, 0, 0, NULL); Draw a smaller figure


G.dispose ();


Output as File


Imageio.write (Tag, "JPEG", New File (Descdir


+ "_r" + i + "_c" + j + ". jpg"));


}


}


}


catch (Exception e) {


E.printstacktrace ();


}


}

/**


* Image Cutting (Specify the width and height of the slice)


* @param srcimagefile Source image Address


* @param descdir Slice destination Folder


* @param destwidth The width of the target slice. Default 200


* @param destheight the target slice height. Default 150


*/


Public final static void Cut3 (String srcimagefile, String Descdir,


int destwidth, int destheight) {


try {


if (destwidth&lt;=0) destwidth = 200; Slice width


if (destheight&lt;=0) destheight = 150; Slice height


Reading source Images


BufferedImage bi = imageio.read (new File (Srcimagefile));


int srcwidth = Bi.getheight (); Source Chart Width


int srcheight = Bi.getwidth (); Source Diagram Height


if (Srcwidth &gt; Destwidth &amp;&amp; srcheight &gt; Destheight) {


Image img;


ImageFilter Cropfilter;


Image image = Bi.getscaledinstance (Srcwidth, Srcheight, Image.scale_default);


int cols = 0; Slice Horizontal Quantity


int rows = 0; Slice portrait number


Calculate the horizontal and vertical number of slices


if (srcwidth% Destwidth = = 0) {


cols = Srcwidth/destwidth;


} else {


cols = (int) Math.floor (srcwidth/destwidth) + 1;


}


if (srcheight% Destheight = = 0) {


rows = srcheight/destheight;


} else {


rows = (int) Math.floor (srcheight/destheight) + 1;


}


Looping to create slices


Improved idea: Whether multithreading can speed up the cutting speed


for (int i = 0; i &lt; rows; i++) {


for (int j = 0; J &lt; cols; J + +) {


The four parameters are image starting coordinates and width-height respectively.


That is: cropimagefilter (int x,int y,int width,int height)


Cropfilter = new CropImageFilter (J * destwidth, I * destheight,


Destwidth, Destheight);


img = Toolkit.getdefaulttoolkit (). CreateImage (


New FilteredImageSource (Image.getsource (),


Cropfilter));


BufferedImage tag = new BufferedImage (Destwidth,


Destheight, Bufferedimage.type_int_rgb);


Graphics g = tag.getgraphics ();


G.drawimage (IMG, 0, 0, NULL); Draw a smaller figure


G.dispose ();


Output as File


Imageio.write (Tag, "JPEG", New File (Descdir


+ "_r" + i + "_c" + j + ". jpg"));


}


}


}


catch (Exception e) {


E.printstacktrace ();


}


}

/**


* Image type conversion: Gif-&gt;jpg, Gif-&gt;png, Png-&gt;jpg, Png-&gt;gif (X), bmp-&gt;png


* @param srcimagefile Source image Address


* @param formatname String containing informal names: JPG, JPEG, GIF, etc.


* @param destimagefile Target image address


*/


Public final static void convert (String srcimagefile, String FormatName, String destimagefile) {


try {


File F = new file (srcimagefile);


F.canread ();


F.canwrite ();


BufferedImage src = imageio.read (f);


Imageio.write (SRC, formatname, new File (Destimagefile));


catch (Exception e) {


E.printstacktrace ();


}


}

/**


* Color to black and white


* @param srcimagefile Source image Address


* @param destimagefile Target image address


*/


Public final static void Gray (string srcimagefile, String destimagefile) {


try {


BufferedImage src = imageio.read (new File (Srcimagefile));


ColorSpace cs = colorspace.getinstance (Colorspace.cs_gray);


Colorconvertop op = new Colorconvertop (cs, NULL);


src = op.filter (src, null);


Imageio.write (SRC, "JPEG", New File (Destimagefile));


catch (IOException e) {


E.printstacktrace ();


}


}

/**


* Add a text watermark to the picture


* @param presstext Watermark Text


* @param srcimagefile Source image Address


* @param destimagefile Target image address


* @param the font name of the FontName watermark


* @param the font style of the FontStyle watermark


* @param the font color of a color watermark


* @param the font size of the fontsize watermark


* @param x Correction


* @param y correction positive


* @param alpha Transparency: alpha must be a floating-point number within the range [0.0, 1.0] (containing the boundary value)


*/


Public final static void Presstext (String presstext,


String Srcimagefile, String destimagefile, String fontname,


int FontStyle, color color, int fontsize,int x,


int y, float alpha) {


try {


File img = new file (srcimagefile);


Image src = Imageio.read (img);


int width = src.getwidth (null);


int height = src.getheight (null);


BufferedImage image = new BufferedImage (width, height,


BUFFEREDIMAGE.TYPE_INT_RGB);


Graphics2D g = image.creategraphics ();


G.drawimage (SRC, 0, 0, width, height, null);


G.setcolor (color);


G.setfont (New Font (FontName, FontStyle, FontSize));


G.setcomposite (Alphacomposite.getinstance (Alphacomposite.src_atop,


Alpha));


Draw watermark text at specified coordinates


g.DrawString (Presstext, (Width-getlength (presstext) * fontsize))


/2 + x, (height-fontsize)/2 + y);


G.dispose ();


Imageio.write ((bufferedimage) image, "JPEG", new File (Destimagefile));//output to file stream


catch (Exception e) {


E.printstacktrace ();


}


}

/**


* Add a text watermark to the picture


* @param presstext Watermark Text


* @param srcimagefile Source image Address


* @param destimagefile Target image address


* @param fontname Font Name


* @param fontstyle font style


* @param color font colors


* @param fontsize Font size


* @param x Correction


* @param y correction positive


* @param alpha Transparency: alpha must be a floating-point number within the range [0.0, 1.0] (containing the boundary value)


*/


Public final static void PressText2 (String presstext, String srcimagefile,string destimagefile,


String fontname, int fontstyle, color color, int fontsize, int x,


int y, float alpha) {


try {


File img = new file (srcimagefile);


Image src = Imageio.read (img);


int width = src.getwidth (null);


int height = src.getheight (null);


BufferedImage image = new BufferedImage (width, height,


BUFFEREDIMAGE.TYPE_INT_RGB);


Graphics2D g = image.creategraphics ();


G.drawimage (SRC, 0, 0, width, height, null);


G.setcolor (color);


G.setfont (New Font (FontName, FontStyle, FontSize));


G.setcomposite (Alphacomposite.getinstance (Alphacomposite.src_atop,


Alpha));


Draw watermark text at specified coordinates


g.DrawString (Presstext, (Width-getlength (presstext) * fontsize))


/2 + x, (height-fontsize)/2 + y);


G.dispose ();


Imageio.write ((bufferedimage) image, "JPEG", New File (Destimagefile));


catch (Exception e) {


E.printstacktrace ();


}


}

/**


* Add a picture watermark to the picture


* @param pressimg watermark Picture


* @param srcimagefile Source image Address


* @param destimagefile Target image address


* @param x Correction value. Default in the middle


* @param y correction value. Default in the middle


* @param alpha Transparency: alpha must be a floating-point number within the range [0.0, 1.0] (containing the boundary value)


*/


Public final static void Pressimage (String pressimg, String srcimagefile,string destimagefile,


int x, int y, float alpha) {


try {


File img = new file (srcimagefile);


Image src = Imageio.read (img);


int wideth = Src.getwidth (null);


int height = src.getheight (null);


BufferedImage image = New BufferedImage (wideth, height,


BUFFEREDIMAGE.TYPE_INT_RGB);


Graphics2D g = image.creategraphics ();


G.drawimage (SRC, 0, 0, wideth, height, null);


Watermark File


Image Src_biao = Imageio.read (new File (pressimg));


int wideth_biao = Src_biao.getwidth (null);


int height_biao = Src_biao.getheight (null);


G.setcomposite (Alphacomposite.getinstance (Alphacomposite.src_atop,


Alpha));


G.drawimage (Src_biao, (Wideth-wideth_biao)/2,


(Height-height_biao)/2, Wideth_biao, Height_biao, NULL);


Watermark File End


G.dispose ();


Imageio.write ((bufferedimage) image, "JPEG", New File (Destimagefile));


catch (Exception e) {


E.printstacktrace ();


}


}

/**


* Calculate the length of text (two characters in one Chinese)


* @param text


* @return


*/


Public final static int getlength (String text) {


int length = 0;


for (int i = 0; i &lt; text.length (); i++) {


if (New String (Text.charat (i) + ""). GetBytes (). length &gt; 1) {


length = 2;


} else {


length = 1;


}


}


return LENGTH/2;


}


}


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.