CSDN博客

img peter207

用java生成jpg图片

发表于2005/6/10 11:40:00  4408人阅读

分类: Java

package other.pic;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.RandomAccessFile;
import java.awt.image.BufferedImage;
import java.awt.*;
import java.util.Random;

/**
 * Created by IntelliJ IDEA.
 * User: Administrator
 * Date: 2005-6-10
 * Time: 11:19:49
 * This class can create jpg picture.
 * To change this template use File | Settings | File Templates.
 */
public class ChartGraphics {
    BufferedImage image;

    void createImage(String fileLocation) {
        try {
            FileOutputStream fos = new FileOutputStream(fileLocation);
            BufferedOutputStream bos = new BufferedOutputStream(fos);
            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(bos);
            encoder.encode(image);
            bos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void graphicsGeneration(int h1, int h2, int h3, int h4, int h5) {

        final int X = 10;
        int imageWidth = 300;//图片的宽度
        int imageHeight = 300;//图片的高度
        int columnWidth = 30;//柱的宽度
        int columnHeight = 200;//柱的最大高度

        // ChartGraphics chartGraphics = new ChartGraphics();
        image = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_INT_RGB);
        Graphics graphics = image.getGraphics();
        graphics.setColor(Color.white);
        graphics.fillRect(0, 0, imageWidth, imageHeight);
        graphics.setColor(Color.red);
        graphics.drawRect(X + 1 * columnWidth, columnHeight - h1, columnWidth, h1);
        graphics.drawRect(X + 2 * columnWidth, columnHeight - h2, columnWidth, h2);
        graphics.drawRect(X + 3 * columnWidth, columnHeight - h3, columnWidth, h3);
        graphics.drawRect(X + 4 * columnWidth, columnHeight - h4, columnWidth, h4);
        graphics.drawRect(X + 5 * columnWidth, columnHeight - h5, columnWidth, h5);
        createImage("D://Temp//chart.jpg");
    }

    public static void main(String[] args) {
        int[] height = {40,50,16,22,85};
          ChartGraphics cg=new ChartGraphics();
        try {
            for (int i = 0; i < 5; i++) {
                cg.graphicsGeneration(height[0],height[1],height[2],height[3],height[4]);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }


    }
}

以下是生成的图片

----------------------------------

阅读全文
0 0

相关文章推荐

img
取 消
img