Accumulate Kuibu, Poly stream------java information generation picture

Source: Internet
Author: User

Requirements:
This is the problem that comes up when you do a certificate. at that time, the demand is to be able to print the certificate online, the first operation is to print the HTML directly, and has been lined up (with the Jqprint plug-in) to print, in the printing encountered a compatibility problem, in addition, because the background image loading is slower than the text loading, the first load of text appears after the phenomenon of the picture, It is very unprofessional, then the use of the information into a picture, and then directly print the picture, no matter how to print, will not change, and can export pictures, the picture for more fine operation.
Code writing:
First of all, say the code First:
Package Com.jzba.utils;import Java.awt.basicstroke;import Java.awt.color;import java.awt.font;import Java.awt.graphics;import Java.awt.graphics2d;import Java.awt.image;import Java.awt.renderinghints;import Java.awt.transparency;import Java.awt.image.bufferedimage;import Java.io.file;import Java.io.FileInputStream; Import Java.io.fileoutputstream;import java.io.ioexception;import java.io.inputstream;import java.io.OutputStream; Import Java.text.simpledateformat;import java.util.date;import Java.util.map;import Java.util.random;import Javax.imageio.imageio;import Javax.swing.imageicon;import Com.sun.image.codec.jpeg.imageformatexception;import Com.sun.image.codec.jpeg.jpegcodec;import Com.sun.image.codec.jpeg.jpegimageencoder;public class ImgUtils {private static int newwidth=0,newheight=0,newx=0,newy=0;public static void main (string[] args) throws exception{--1, local test String Over= "D:/zz/1/over.png"; Color color = new color (100,100,100); Imageutil iu=new imageutil (); Map Map=iu.getimagesizebybufFeredimage ("D:/zz/ceshi.png");--note: see the code under int width= (integer) map.get ("width"), int height= (integer) map.get ("height") ); float bili=width/height;if (width>height) {newwidth=660;newheight=height*660/width;newx=600;newy=1160+330- NEWHEIGHT/2;} ELSE{NEWHEIGHT=660;NEWWIDTH=WIDTH*660/HEIGHT;NEWY=1160;NEWX=600+330-NEWWIDTH/2;} String Temp1=createcard ("D:/zz/1/background.png", "D:/zz/1/ceshi.png", "D:/zz/1/code.bmp", "D:/zz/1/temp1.png", NEWX,NEWY,600,1210,NEWWIDTH,NEWHEIGHT,250,250); String Temp1=createcard ("D:/zz/1/background.png", "d:/zz/1/ceshi2.jpg", "D:/zz/1/code.bmp", "D:/zz/1/temp1.png",   100,100,600,1210,newwidth,newheight,250,250); ImageIcon Imgicon = new ImageIcon (TEMP1);   Image theimg = Imgicon.getimage ();   int w = theimg.getwidth (null);   int h = theimg.getheight (null);   BufferedImage bufimg = new BufferedImage (W, H, Bufferedimage.type_int_rgb);   Get graphics2d graphics2d g = bufimg.creategraphics (); G.setrenderinghint (renderinghints.key_rendering, renderinghints.value_render_quality);  Paint bufimg = G.getdeviceconfiguration (). Createcompatibleimage (W, H, transparency.translucent);   G.dispose ();   g = Bufimg.creategraphics ();   G.setstroke (New Basicstroke (1));   G.drawimage (theimg, 0, 0, W, h, NULL);//Background map start position g.setcolor (color);   Font NF = loadfont ("D:/zz/simhei.ttf", 60);       Font Nf2 = Loadfont ("D:/zz/simhei.ttf", 50);   G.setfont (NF);   g.DrawString ("Secret", 2500,1040);//G.setfont (NF2); g.DrawString ("Secret", 1920,1190);//g.DrawString ("Secret", 1920x1080, 1290);//g.DrawString ("Secret", 1920x1080, 1390);//G.drawstri  Ng ("Secret", 1920x1080, 1490);//g.DrawString ("Secret", 1920x1080, 1590);//g.DrawString ("Secret", 1920x1080, 1700);//g.DrawString   ", 1920, 1800);///Release Object file Tofile=new file (over);   Imageio.write (bufimg, "PNG", tofile); G.dispose ();}         /** * * Combine the images you want to add to add * @param backspath the path to the background image * @param the path to the Titleimgpath thumbnail image * ... * * @return Topath The path of the image after compositing * * */public static string Createcard (string backspath,string titleimgpath,string codEimgpath,string topath,int x,int y,int newx,int newy,int widthtitle,int heighttitle,int codeWidth,int codeHeight) {try {I Nputstream imageback=new FileInputStream (Backspath);//Background map InputStream imagetitle=new FileInputStream (TitleImgPath); Thumbnail image inputstream imagecode=new fileinputstream (Codeimgpath);//QR code picture BufferedImage backimg=imageio.read (im        Ageback);        BufferedImage Titleimg=imageio.read (Imagetitle);        BufferedImage Codeimg=imageio.read (Imagecode);        System.out.println ("*****graphics****" +backspath);        Graphics G=backimg.getgraphics ();        System.out.println ("*****graphics****1");        G.drawimage (Titleimg,x,y,widthtitle,heighttitle,null);        System.out.println ("*****graphics****2");        G.drawimage (Codeimg,newx,newy,codewidth,codeheight,null);        System.out.println ("*****graphics****3");        OutputStream outimage=new FileOutputStream (Topath); System.out.println ("*****graphics****4");//JPEGImageEncoder Enc=jpegCodec.createjpegencoder (outimage);--there is a problem here//System.out.println ("*****graphics****5");--under window can not be done under Linux        /enc.encode (BACKIMG);        File Tofile=new file (Topath);        Imageio.write (backimg, "PNG", ToFile);//SYSTEM.OUT.PRINTLN ("* * * * *" +backspath);        Imageback.close ();//Turn off the output port imagetitle.close ();        Imagecode.close (); Outimage.close ();} catch (Exception e) {e.printstacktrace ();} return topath;} /** * Combine the text information you want to add to add * * * **/public static string Addcardword (String filepath,string topath,int fontsize, Color ma Rkcontentcolor,string fontpath,string code,string type,string artist,string artname,string description,String Material,string artisttype,string recordescription,string releasedate,int codex,int codey,int typex,int typey,int Artistx,int artisty,int artnamex,int artnamey,int descriptionx,int descriptiony,int materialx,int materialy,int Artisttypex,int Artisttypey,int recordescriptionx,int recordescriptiony) throws Exception{imageicon ImgIcon =New ImageIcon (FilePath);   Image theimg = Imgicon.getimage ();   int w = theimg.getwidth (null);   int h = theimg.getheight (null);   BufferedImage bufimg = new BufferedImage (W, H, Bufferedimage.type_int_rgb);   Get graphics2d graphics2d g = bufimg.creategraphics ();   G.setrenderinghint (renderinghints.key_rendering, renderinghints.value_render_quality);   Paint bufimg = G.getdeviceconfiguration (). Createcompatibleimage (W, H, transparency.translucent);   G.dispose ();   g = Bufimg.creategraphics ();   G.setstroke (New Basicstroke (1));   G.drawimage (theimg, 0, 0, W, h, NULL);//Background map start position g.setcolor (Markcontentcolor);       Font NF = loadfont (fontpath,fontsize);   G.setfont (NF);   g.DrawString (Code, Codex, Codey);   g.DrawString (Type, Typex, typey);   g.DrawString (artist, ARTISTX, Artisty);   g.DrawString (Artname, Artnamex, Artnamey);   g.DrawString (description, Descriptionx, descriptiony);   g.DrawString (material, materialx, materialy); g.DrawString (Artisttype, Artisttypex, Artisttypey);  g.DrawString (Recordescription, Recordescriptionx, recordescriptiony);   Release Object file Tofile=new file (Topath);   Imageio.write (bufimg, "PNG", tofile);   G.dispose (); return topath;} /** * Add a picture to the picture * @param backspath background Image path * @param uppath Add picture path * @param topath generate picture Path * @param x the lateral displacement of the image added to the background image, with the upper left corner as the label   Quasi * @param y the vertical displacement of the picture on the background image, with the upper-left corner as the standard * @param width of the image added to width * @param height of the picture added * @return Topath String Returns the path of the resulting picture *            * **/public static string Addimg2img (String backspath,string uppath,string topath,int x,int y,int width,int height) {               try {inputstream imagein=new fileinputstream (Backspath);               InputStream imagein2=new FileInputStream (Uppath);               BufferedImage Image=imageio.read (ImageIn);//read background image BufferedImage Image2=imageio.read (imagein2);//Read the picture to be added Graphics g=image.getgraphics ();//The background image as a drawing panel g.drawimage (image2,x,y,width,height,null);//In the background image of the base To add images to OutputStream OUtimage=new FileOutputStream (Topath);//Open export picture path JPEGImageEncoder enc=jpegcodec.createjpegencoder (outImage);               Enc.encode (image);//Generate Picture Output imagein.close ();//close open import, Export channel Imagein2.close ();   Outimage.close ();   } catch (Exception e) {e.printstacktrace ();    } return Topath; }/** * Add text to the picture * @param filePath background Image path * @param topath generate picture Path * @param markcontent added text content * @param fontsize words to add text Body size * @param markcontentcolor Add text color * @param fontpath Add text font * @param x the lateral displacement of the picture you added on the background image, with the upper left corner as standard * @param y Add the picture on the background image Vertical displacement with the upper left corner as standard * @return Topath String Returns the path to the generated picture * **/public static string Addword2img (String filepath,string topath , String markcontent,int fontsize, Color markcontentcolor,string fontpath,int x,int y) throws Exception {ImageIcon IMGI   con = new ImageIcon (FilePath);   Image theimg = Imgicon.getimage ();   int w = theimg.getwidth (null);   int h = theimg.getheight (null); BufferedImage BUfimg = new BufferedImage (W, H, Bufferedimage.type_int_rgb);   Get graphics2d graphics2d g = bufimg.creategraphics ();   G.setrenderinghint (renderinghints.key_rendering, renderinghints.value_render_quality);   Paint bufimg = G.getdeviceconfiguration (). Createcompatibleimage (W, H, transparency.translucent);   G.dispose ();   g = Bufimg.creategraphics ();   G.setstroke (New Basicstroke (1)); G.drawimage (theimg, 0, 0, W, h, NULL);//background map starting position g.setcolor (markcontentcolor);//color setting for added text Font NF = Loadfont (fontpat       H,fontsize); G.setfont (NF);//font and font size settings for added text g.drawstring (markcontent, x, y);//Add text to the position specified by the picture//Release the object file Tofile=new file (topath   )///Open Export channel Imageio.write (BUFIMG, "PNG", tofile);//Paint g.dispose ();  return topath; /** * Set font and font size for added text * @param fontfilename external font name * @param fontsize Add text font size * @param markcontentcolor Add text color * @ return dynamicfontpt font corresponding setting for text * * **/public static font Loadfont (String fontfilename, float fontSize) throws Excepti On//First parameterThe number is the external font name, and the second is the font size {File File = new file (fontfilename); FileInputStream aixing = new FileInputStream (file); Font Dynamicfont = Font.createfont (Font.truetype_font, aixing); Font dynamicfontpt = Dynamicfont.derivefont (fontSize); Aixing.close (); return dynamicfontpt;}}
Note: In the code called to the previous article to obtain the size of the corresponding class, the purpose here is that for different works, may be horizontal or vertical picture, in order to ensure that the picture is not distorted, the picture is displayed in a fixed area,like here:
The default is a section of 660*660 area, first of all to determine whether to add a picture is a horizontal bar or vertical bar, if it is a horizontal bar, then the width is greater than the height, then set a large width of 660, corresponding to the proportion: 660/width = Required height/actual height, you can get the corresponding height value, And this height value is certainly less than 660, because it is a horizontal bar, so the width of the displacement is the corresponding displacement of the specified area, here is 600px, and the height of displacement, it should be added to the upper left corner of the image, the height of the background image of half minus the image of the current height of half; The height is greater than the width, then the height is set to 660, and so on, to get the corresponding displacement and size. To achieve the effect of what it looks like, let us briefly look at:(this is height greater than width)
(this is width greater than height)

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Accumulate Kuibu, Poly stream------java information generation picture

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.