Java generates an image and java generates an image.

Source: Internet
Author: User

Java generates an image and java generates an image.

Public class CreateImage {public static void main (String [] args) throws Exception {int width = 100; int height = 100; String s = "hello "; file file = new File ("/Users/tengxin/Pictures/image.jpg"); Font font = new Font ("Serif", Font. BOLD, 10); BufferedImage bi = new BufferedImage (width, height, BufferedImage. TYPE_INT_RGB); Graphics2D g2 = (Graphics2D) bi. getGraphics (); g2.setBackground (Color. WHITE); g2.clearRect (0, 0, width, height); g2.setPaint (Color. RED); FontRenderContext context = g2.getFontRenderContext (); Rectangle2D bounds = font. getStringBounds (s, context); double x = (width-bounds. getWidth ()/2; double y = (height-bounds. getHeight ()/2; double ascent =-bounds. getY (); double baseY = y + ascent; g2.drawString (s, (int) x, (int) baseY); ImageIO. write (bi, "jpg", file );}}



Java random Image Generation

You do not need to change your code too much, that is, the JLabel array labels is only a JLabel array and does not create a real JLabel object. Therefore, Add labels [I] = new JLabel (); that's all.
Source code:
Import javax. swing .*;
Import java. awt .*;

Public class Exercise_4 {

Public static void main (String [] args ){

JFrame frame = new JFrame ("Exercise 4 ");
Frame. setLayout (new GridLayout (3, 3 ));
Frame. setSize (300,300 );
Frame. setVisible (true );
Frame. setdefaclocloseoperation (JFrame. EXIT_ON_CLOSE );

JLabel [] labels = new JLabel [9];

For (int I = 0; I <9; I ++ ){
Labels [I] = new JLabel ();
Frame. add (labels [I]);

Int num = (int) (Math. random () * 3 ));

If (num = 0 ){
Labels [I]. setIcon (new ImageIcon ("X.jpg "));
}

Else if (num = 1 ){
Labels [I]. setIcon (new ImageIcon ("0.jpg "));
}
}
}
}

JAVA generates multiple images in one Action and displays them on JSP.

How can I display images on your jsp page? Is used?

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.