BufferedImage&Graphics2D簡談

類結構

java.lang.Object
     |____ java.awt.Image
           |____  java.awt.image.BufferedImage
java.lang.Object
     |____ java.awt.Graphics
           |____ java.awt.Graphics2D

API鏈接

BufferedImage
Graphics2D

簡介

public class BufferedImage extends Image implements WritableRenderedImage, Transparency

BufferedImage 子類描述具有可訪問圖像數據緩衝區的 Image。BufferedImage 由圖像數據的 ColorModel 和 Raster 組成。Raster 的 SampleModel 中 band 的數量和類型必須與 ColorModel 所要求的數量和類型相匹配,以表示其顏色和 alpha 分量。所有 BufferedImage 對象的左上角座標都爲 (0, 0)。因此,用來構造 BufferedImage 的任何 Raster 都必須滿足:minX=0 且 minY=0。
此類依靠 Raster 的數據獲取方法、數據設置方法,以及 ColorModel 的顏色特徵化方法。

public abstract class Graphics2D extends Graphics

此 Graphics2D 類擴展 Graphics 類,以提供對幾何形狀、座標轉換、顏色管理和文本佈局更爲複雜的控制。它是用於在 Java(tm) 平臺上呈現二維形狀、文本和圖像的基礎類。

具體實現

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

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 Test2 {

    /**
     * @param args
     */
    public static void main(String[] args) {
        ImageIcon vmImageIcon = new ImageIcon("D:/jpg/template.jpg");
        Image image = vmImageIcon.getImage();
        int width = image.getWidth(null);
        int height = image.getHeight(null);
        BufferedImage bufferedImage = new BufferedImage(width, height,
                BufferedImage.TYPE_INT_RGB);
        Graphics2D graphics2d = bufferedImage.createGraphics();
        graphics2d.drawImage(image, 0, 0, null);
        graphics2d.setColor(Color.BLACK);
        graphics2d.setFont(new Font(null, Font.ITALIC, 30));
        graphics2d.drawString("123", 680, 200);
        graphics2d.dispose();

        try {
            FileOutputStream outPic = new FileOutputStream("D:/jpg/done.jpg");
            JPEGImageEncoder imageEncoder = JPEGCodec.createJPEGEncoder(outPic);
            imageEncoder.encode(bufferedImage);
            outPic.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (ImageFormatException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章