1. Image Generation with BufferedImage
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 | package javaimage; import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.Arrays; import java.util.List; import javax.imageio.ImageIO; public class JavaImage { public JavaImage() { } BufferedImage loadImage() { BufferedImage bi = null; try { bi= ImageIO.read(new File("D:/a.png")); int w = bi.getWidth(null); int h = bi.getHeight(null); if (bi.getType() != BufferedImage.TYPE_INT_RGB) { BufferedImage bi2 = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB); Graphics big = bi2.getGraphics(); big.drawImage(bi, 0, 0, null); bi = bi2; } } catch (IOException e) { e.printStackTrace(); } return bi; } BufferedImage makeImage(int width, int height) { BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); return image; } boolean saveImage(BufferedImage image, String filename) { try { ImageIO.write(image, "png", new File(filename)); return true; } catch (IOException e) { e.printStackTrace(); return false; } } void testDraw(BufferedImage image) { Graphics2D g2 = image.createGraphics(); /* g2.drawImage(picOfFace1, 0, 0, null); g2.drawImage(picOfFace2, 50, 0, null); */ g2.setBackground(Color.white); g2.setColor(Color.blue); g2.clearRect(0, 0, 200, 100); g2.drawRect(0,0,200-1,50); g2.drawString("Hello World !", 10,10); g2.fillRect(0,50,200-1,100); g2.setColor(Color.white); g2.drawString("Java Graphics !", 10, 60); g2.dispose(); } void printImageFormats() { List<String> f = Arrays.asList(ImageIO.getWriterFormatNames()); f.forEach(System.out::println); } public static void main(String[] args) { JavaImage ji = new JavaImage(); ji.printImageFormats(); BufferedImage image = ji.makeImage(200,100); ji.testDraw(image); ji.saveImage(image, "D:/a.png"); } } |
Result:
JPG jpg bmp BMP gif GIF WBMP png PNG wbmp jpeg JPEG
Result Image: (D:/a.png)
댓글 없음:
댓글 쓰기