Java Code Examples for java.awt.image.BufferedImage#TYPE_3BYTE_BGR

The following examples show how to use java.awt.image.BufferedImage#TYPE_3BYTE_BGR . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
static String getImageTypeName(int type) {
    switch(type) {
        case BufferedImage.TYPE_INT_RGB:
            return "TYPE_INT_RGB";
        case BufferedImage.TYPE_3BYTE_BGR:
            return "TYPE_3BYTE_BGR";
        case BufferedImage.TYPE_USHORT_555_RGB:
            return "TYPE_USHORT_555_RGB";
        case BufferedImage.TYPE_BYTE_GRAY:
            return "TYPE_BYTE_GRAY";
        case BufferedImage.TYPE_BYTE_BINARY:
            return "TYPE_BYTE_BINARY";
        default:
            return "TBD";
    }
}
 
Example 2
Source Project: DataVec   File: TestImageLoader.java    License: Apache License 2.0 6 votes vote down vote up
private BufferedImage makeRandomBufferedImage(boolean alpha) {
    int w = rng.nextInt() % 100 + 100;
    int h = rng.nextInt() % 100 + 100;
    int type = alpha ? BufferedImage.TYPE_4BYTE_ABGR : BufferedImage.TYPE_3BYTE_BGR;
    BufferedImage img = new BufferedImage(w, h, type);
    for (int i = 0; i < h; ++i) {
        for (int j = 0; j < w; ++j) {
            int a = (alpha ? rng.nextInt() : 1) & 0xff;
            int r = rng.nextInt() & 0xff;
            int g = rng.nextInt() & 0xff;
            int b = rng.nextInt() & 0xff;
            int v = (a << 24) | (r << 16) | (g << 8) | b;
            img.setRGB(j, i, v);
        }
    }
    return img;
}
 
Example 3
Source Project: diirt   File: LineTimeGraph2DRendererTest.java    License: MIT License 6 votes vote down vote up
@Test
public void testMultilineLabelsEnd() throws Exception {
//tests what happens if we have a date and time for the last label
//on the graph
    Instant start = TimeScalesTest.create(2014, 12, 31, 23, 30, 0, 0);
    TimeSeriesDataset data = TimeSeriesDatasets.timeSeriesOf(new ArrayDouble( 1 , 2 , 3 , 4 ),
            Arrays.asList(start,
                    start.plus( TimeDuration.ofMinutes( 10 ) ) ,
                    start.plus( TimeDuration.ofMinutes( 20 ) ) ,
                    start.plus( TimeDuration.ofMinutes( 30 ) )
            ));
    BufferedImage image = new BufferedImage(500, 200, BufferedImage.TYPE_3BYTE_BGR);
    LineTimeGraph2DRenderer renderer = new LineTimeGraph2DRenderer(500, 200);
    renderer.update(new LineTimeGraph2DRendererUpdate().interpolation(InterpolationScheme.LINEAR ));
    Graphics2D graphics = (Graphics2D) image.getGraphics();
    renderer.draw(graphics, data);
    ImageAssert.compareImages("lineTimeGraph.multiLineLabels.2", image);
}
 
Example 4
Source Project: Pixie   File: ResizeTest.java    License: MIT License 6 votes vote down vote up
@Test
public void testResizeImage_02() {
    final String testDescription = "----------resizeImage_02----------\n"
            + " Summary: Test of resizeImage(BufferedImage) method, of class Resize\n"
            + " Description: Check if an image has the same size when the resize is set to 1.0. Input image has a size of 100x100, the resize is set to (1.0, 1.0).\n"
            + " Pre-conditions: none\n"
            + " Conditions: none\n"
            + " Expected result: It shall output an image of size 100x100; no errors or exceptions shall occur.\n";
    System.out.println(testDescription);

    BufferedImage origImg = new BufferedImage(100, 100, BufferedImage.TYPE_3BYTE_BGR);
    Resize instance = new Resize(1.0, 1.0);
    Dimension expDim = new Dimension(100, 100);
    BufferedImage resultImg = instance.resizeImage(origImg);
    Dimension resultDim = new Dimension(resultImg.getWidth(), resultImg.getHeight());
    assertEquals(expDim, resultDim);
}
 
Example 5
private static String describeType(int type) {
    switch(type) {
    case BufferedImage.TYPE_3BYTE_BGR:
        return "TYPE_3BYTE_BGR";
    case BufferedImage.TYPE_4BYTE_ABGR:
        return "TYPE_4BYTE_ABGR";
    case BufferedImage.TYPE_BYTE_GRAY:
        return "TYPE_BYTE_GRAY";
    case BufferedImage.TYPE_INT_ARGB:
        return "TYPE_INT_ARGB";
    case BufferedImage.TYPE_INT_BGR:
        return  "TYPE_INT_BGR";
    case BufferedImage.TYPE_INT_RGB:
        return "TYPE_INT_RGB";
    case BufferedImage.TYPE_BYTE_INDEXED:
        return "TYPE_BYTE_INDEXED";
    default:
        throw new RuntimeException("Test FAILED: unknown type " + type);
    }
}
 
Example 6
Source Project: pumpernickel   File: ScalingIterator.java    License: MIT License 6 votes vote down vote up
public int getPixelSize() {
	switch (imageType) {
	case PixelIterator.TYPE_3BYTE_RGB:
	case BufferedImage.TYPE_3BYTE_BGR:
		return 3;
	case PixelIterator.TYPE_4BYTE_ARGB:
	case PixelIterator.TYPE_4BYTE_ARGB_PRE:
	case BufferedImage.TYPE_4BYTE_ABGR:
	case BufferedImage.TYPE_4BYTE_ABGR_PRE:
		return 4;
	case BufferedImage.TYPE_BYTE_GRAY:
		return 1;
	}
	throw new RuntimeException("unexpected condition: imageType = "
			+ imageType);
}
 
Example 7
Source Project: diirt   File: LineTimeGraph2DRendererTest.java    License: MIT License 6 votes vote down vote up
@Test
public void extraGraphAreaDegenerate2() throws Exception {
//test going backwards in time with no extra graph area. Essentially,
//our data points extend the whole x axis range, but the last data point
//has x value less than other data points
    Instant start = TimeScalesTest.create(2013, 4, 5, 11, 13, 3, 900);
    TimeSeriesDataset data = TimeSeriesDatasets.timeSeriesOf(new ArrayDouble(1,2,3,4,5,-1),
            Arrays.asList(start,
            start.plus(Duration.ofMillis(3000)),
            start.plus(Duration.ofMillis(6000)),
            start.plus(Duration.ofMillis(8500)),
            start.plus(Duration.ofMillis(12500)),
            start.plus(Duration.ofMillis(1500))));
    BufferedImage image = new BufferedImage(300, 200, BufferedImage.TYPE_3BYTE_BGR);
    LineTimeGraph2DRenderer renderer = new LineTimeGraph2DRenderer(300, 200);
    renderer.update(new LineTimeGraph2DRendererUpdate().interpolation(InterpolationScheme.PREVIOUS_VALUE)
           .timeAxisRange(TimeAxisRanges.absolute(TimeInterval.between(start,
                   start.plus(Duration.ofMillis(12500))))));
    Graphics2D graphics = (Graphics2D) image.getGraphics();
    renderer.draw(graphics, data);
    ImageAssert.compareImages("lineTimeGraph.extraGraphArea.degenerate.2", image);
}
 
Example 8
private static String describeType(int type) {
    switch(type) {
    case BufferedImage.TYPE_3BYTE_BGR:
        return "TYPE_3BYTE_BGR";
    case BufferedImage.TYPE_4BYTE_ABGR:
        return "TYPE_4BYTE_ABGR";
    case BufferedImage.TYPE_BYTE_GRAY:
        return "TYPE_BYTE_GRAY";
    case BufferedImage.TYPE_INT_ARGB:
        return "TYPE_INT_ARGB";
    case BufferedImage.TYPE_INT_BGR:
        return  "TYPE_INT_BGR";
    case BufferedImage.TYPE_INT_RGB:
        return "TYPE_INT_RGB";
    case BufferedImage.TYPE_BYTE_INDEXED:
        return "TYPE_BYTE_INDEXED";
    default:
        throw new RuntimeException("Test FAILED: unknown type " + type);
    }
}
 
Example 9
/**
     *   * 对图像解码返回RGB格式矩阵数据
     *   * @param image
     *   * @return
     *   
     */
//    public static byte[] getMatrixRGB(BufferedImage image) {
//        byte[] matrixRGB;
//        if (isRGB3Byte(image)) {
//            matrixRGB = (byte[]) image.getData().getDataElements(0, 0, image.getWidth(), image.getHeight(), null);
//        } else {
//            // 转RGB格式
//            BufferedImage rgbImage = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_3BYTE_BGR);
//            new ColorConvertOp(ColorSpace.getInstance(ColorSpace.CS_sRGB), null).filter(image, rgbImage);
//            matrixRGB = (byte[]) rgbImage.getData().getDataElements(0, 0, image.getWidth(), image.getHeight(), null);
//        }
//        return matrixRGB;
//    }

    public static BufferedImage bgrToBufferedImage(byte[] data, int width, int height) {
        int type = BufferedImage.TYPE_3BYTE_BGR;
        // bgr to rgb
        byte b;
        for (int i = 0; i < data.length; i = i + 3) {
            b = data[i];
            data[i] = data[i + 2];
            data[i + 2] = b;
        }
        BufferedImage image = new BufferedImage(width, height, type);
        image.getRaster().setDataElements(0, 0, width, height, data);
        return image;
    }
 
Example 10
Source Project: diirt   File: ShowImage.java    License: MIT License 5 votes vote down vote up
public static void main(String args[]) throws Exception {
        Cell1DDataset hist = Cell1DDatasets.linearRange(new ArrayDouble(30, 14, 150, 160, 180, 230, 220, 350, 400, 450, 500,
                                        350, 230, 180, 220, 170, 130, 80, 30, 40), 0.0, 2.0);
        AreaGraph2DRenderer renderer = new AreaGraph2DRenderer(300, 200);
        BufferedImage image = new BufferedImage(renderer.getImageWidth(), renderer.getImageHeight(), BufferedImage.TYPE_3BYTE_BGR);
        Graphics2D graphics = (Graphics2D) image.getGraphics();
        renderer.draw(graphics, hist);
        showImage(image);
//        ImageIO.write(image, "png", new File("hist1dtest.png"));
    }
 
Example 11
Source Project: haxademic   File: AnimatedGifEncoder.java    License: MIT License 5 votes vote down vote up
/**
 * Extracts image pixels into byte array "pixels"
 */
protected void getImagePixels() {
  int w = image.getWidth();
  int h = image.getHeight();
  int type = image.getType();
  if ((w != width) || (h != height) || (type != BufferedImage.TYPE_3BYTE_BGR)) {
    // create new image with right size/format
    BufferedImage temp = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
    Graphics2D g = temp.createGraphics();
    g.drawImage(image, 0, 0, null);
    image = temp;
  }
  pixels = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();
}
 
Example 12
static String getImageTypeName(int type) {
    switch(type) {
        case BufferedImage.TYPE_INT_ARGB:
            return "TYPE_INT_ARGB";
        case BufferedImage.TYPE_INT_RGB:
            return "TYPE_INT_RGB";
        case BufferedImage.TYPE_INT_BGR:
            return "TYPE_INT_BGR";
        case BufferedImage.TYPE_INT_ARGB_PRE:
            return "TYPE_INT_ARGB_PRE";
        case BufferedImage.TYPE_3BYTE_BGR:
            return "TYPE_3BYTE_BGR";
        case BufferedImage.TYPE_4BYTE_ABGR:
            return "TYPE_4BYTE_ABGR";
        case BufferedImage.TYPE_4BYTE_ABGR_PRE:
            return "TYPE_4BYTE_ABGR_PRE";
        case BufferedImage.TYPE_BYTE_BINARY:
            return "TYPE_BYTE_BINARY";
        case BufferedImage.TYPE_BYTE_GRAY:
            return "TYPE_BYTE_GRAY";
        case BufferedImage.TYPE_BYTE_INDEXED:
            return "TYPE_BYTE_INDEXED";
        case BufferedImage.TYPE_USHORT_555_RGB:
            return "TYPE_USHORT_555_RGB";
        case BufferedImage.TYPE_USHORT_565_RGB:
            return "TYPE_USHORT_565_RGB";
        case BufferedImage.TYPE_USHORT_GRAY:
            return "TYPE_USHORT_GRAY";
    }
    return "UNKNOWN";
}
 
Example 13
Source Project: diirt   File: SparklineGraph2DRendererTest.java    License: MIT License 5 votes vote down vote up
@Test
public void oneNaNLinear() throws Exception {

    Point2DDataset data = Point2DTestDatasets.oneNaNDataset();
    BufferedImage image = new BufferedImage(300, 200, BufferedImage.TYPE_3BYTE_BGR);
    SparklineGraph2DRenderer renderer = new SparklineGraph2DRenderer(300, 200);
    renderer.update(renderer.newUpdate().interpolation(InterpolationScheme.LINEAR));
    Graphics2D graphics = (Graphics2D) image.getGraphics();
    renderer.draw(graphics, data);
    ImageAssert.compareImages("sparklineGraph2D.linear.NaN.1", image);
}
 
Example 14
Source Project: diirt   File: Graph2DRendererTest.java    License: MIT License 5 votes vote down vote up
@Test
public void graphArea1() throws Exception {
    Graph2DRenderer renderer = new Graph2DRenderer(300, 200) {

        {
            this.xAreaCoordStart = 4;
            this.xAreaCoordEnd = 296;
            this.yAreaCoordStart = 4;
            this.yAreaCoordEnd = 196;
            this.xReferenceCoords = new ArrayDouble(4.5, 150, 295.5);
            this.yReferenceCoords = new ArrayDouble(195.5, 100, 4.5);
            this.yReferenceLabels = Collections.<String>emptyList();
        }

        @Override
        public Graph2DRendererUpdate newUpdate() {
            return new Graph2DRendererUpdate();
        }
    };

    BufferedImage image = new BufferedImage(300, 200, BufferedImage.TYPE_3BYTE_BGR);
    Graphics2D graphics = (Graphics2D) image.getGraphics();
    renderer.g = graphics;
    renderer.drawBackground();
    renderer.drawGraphArea();
    ImageAssert.compareImages("graph2DArea.1", image);
}
 
Example 15
Source Project: diirt   File: SparklineGraph2DRendererTest.java    License: MIT License 5 votes vote down vote up
@Test
public void maxAndLastOverlap() throws Exception {
    Point2DDataset data = maxLastOverlapDataset();

    //Creates a sparkline graph
    BufferedImage image = new BufferedImage(100, 25, BufferedImage.TYPE_3BYTE_BGR);
    Graphics2D g = (Graphics2D) image.getGraphics();
    SparklineGraph2DRenderer renderer = new SparklineGraph2DRenderer(100, 25);

    renderer.draw(g, data);

    //Compares to correct image
    ImageAssert.compareImages("sparklineGraph2D.maxAndLastOverlap", image);
}
 
Example 16
public static void init() {
    pixelroot = new Group("pixel", "Pixel Access Benchmarks");

    pixeloptroot = new Group(pixelroot, "opts", "Pixel Access Options");
    doRenderTo = new Option.Toggle(pixeloptroot, "renderto",
                                   "Render to Image before test",
                                   Option.Toggle.Off);
    doRenderFrom = new Option.Toggle(pixeloptroot, "renderfrom",
                                     "Render from Image before test",
                                     Option.Toggle.Off);

    // BufferedImage Sources
    bufimgsrcroot = new Group.EnableSet(pixelroot, "src",
                                        "BufferedImage Sources");
    new BufImg(BufferedImage.TYPE_BYTE_BINARY, 1);
    new BufImg(BufferedImage.TYPE_BYTE_BINARY, 2);
    new BufImg(BufferedImage.TYPE_BYTE_BINARY, 4);
    new BufImg(BufferedImage.TYPE_BYTE_INDEXED);
    new BufImg(BufferedImage.TYPE_BYTE_GRAY);
    new BufImg(BufferedImage.TYPE_USHORT_555_RGB);
    new BufImg(BufferedImage.TYPE_USHORT_565_RGB);
    new BufImg(BufferedImage.TYPE_USHORT_GRAY);
    new BufImg(BufferedImage.TYPE_3BYTE_BGR);
    new BufImg(BufferedImage.TYPE_4BYTE_ABGR);
    new BufImg(BufferedImage.TYPE_INT_RGB);
    new BufImg(BufferedImage.TYPE_INT_BGR);
    new BufImg(BufferedImage.TYPE_INT_ARGB);

    // BufferedImage Tests
    bufimgtestroot = new Group(pixelroot, "bimgtests",
                               "BufferedImage Tests");
    new BufImgTest.GetRGB();
    new BufImgTest.SetRGB();

    // Raster Tests
    rastertestroot = new Group(pixelroot, "rastests",
                               "Raster Tests");
    new RasTest.GetDataElements();
    new RasTest.SetDataElements();
    new RasTest.GetPixel();
    new RasTest.SetPixel();

    // DataBuffer Tests
    dbtestroot = new Group(pixelroot, "dbtests",
                           "DataBuffer Tests");
    new DataBufTest.GetElem();
    new DataBufTest.SetElem();
}
 
Example 17
Source Project: Jaffree   File: ProduceGif.java    License: Apache License 2.0 4 votes vote down vote up
public void execute() {
    Path output = Paths.get("test.gif");

    FrameProducer producer = new FrameProducer() {
        private long frameCounter = 0;

        @Override
        public List<Stream> produceStreams() {
            return Collections.singletonList(new Stream()
                    .setType(Stream.Type.VIDEO)
                    .setTimebase(1000L)
                    .setWidth(320)
                    .setHeight(240)
            );
        }

        @Override
        public Frame produce() {
            if (frameCounter > 30) {
                return null;
            }
            System.out.println("Creating frame " + frameCounter);

            BufferedImage image = new BufferedImage(320, 240, BufferedImage.TYPE_3BYTE_BGR);
            Graphics2D graphics = image.createGraphics();
            graphics.setPaint(new Color(frameCounter * 1.0f / 30, 0, 0));
            graphics.fillRect(0, 0, 320, 240);

            Frame videoFrame = new Frame(0, frameCounter * 1000 / 10, image);
            frameCounter++;

            return videoFrame;
        }
    };

    FFmpegResult result = FFmpeg.atPath(ffmpegBin)
            .addInput(
                    FrameInput.withProducer(producer)
            )
            .addOutput(
                    UrlOutput.toPath(output)
            )
            .execute();
}
 
Example 18
/** Redraw a rectanglular area using a proxy graphics
  * To do this we need to know the rectangular area to redraw and
  * the transform & clip in effect at the time of the original drawImage
  *
  */

public void redrawRegion(Rectangle2D region, double scaleX, double scaleY,
                         Shape savedClip, AffineTransform savedTransform)

        throws PrinterException {

    PSPrinterJob psPrinterJob = (PSPrinterJob)getPrinterJob();
    Printable painter = getPrintable();
    PageFormat pageFormat = getPageFormat();
    int pageIndex = getPageIndex();

    /* Create a buffered image big enough to hold the portion
     * of the source image being printed.
     */
    BufferedImage deepImage = new BufferedImage(
                                    (int) region.getWidth(),
                                    (int) region.getHeight(),
                                    BufferedImage.TYPE_3BYTE_BGR);

    /* Get a graphics for the application to render into.
     * We initialize the buffer to white in order to
     * match the paper and then we shift the BufferedImage
     * so that it covers the area on the page where the
     * caller's Image will be drawn.
     */
    Graphics2D g = deepImage.createGraphics();
    ProxyGraphics2D proxy = new ProxyGraphics2D(g, psPrinterJob);
    proxy.setColor(Color.white);
    proxy.fillRect(0, 0, deepImage.getWidth(), deepImage.getHeight());
    proxy.clipRect(0, 0, deepImage.getWidth(), deepImage.getHeight());

    proxy.translate(-region.getX(), -region.getY());

    /* Calculate the resolution of the source image.
     */
    float sourceResX = (float)(psPrinterJob.getXRes() / scaleX);
    float sourceResY = (float)(psPrinterJob.getYRes() / scaleY);

    /* The application expects to see user space at 72 dpi.
     * so change user space from image source resolution to
     *  72 dpi.
     */
    proxy.scale(sourceResX / DEFAULT_USER_RES,
                sourceResY / DEFAULT_USER_RES);
   proxy.translate(
        -psPrinterJob.getPhysicalPrintableX(pageFormat.getPaper())
           / psPrinterJob.getXRes() * DEFAULT_USER_RES,
        -psPrinterJob.getPhysicalPrintableY(pageFormat.getPaper())
           / psPrinterJob.getYRes() * DEFAULT_USER_RES);
   /* NB User space now has to be at 72 dpi for this calc to be correct */
    proxy.transform(new AffineTransform(getPageFormat().getMatrix()));

    proxy.setPaint(Color.black);

    painter.print(proxy, pageFormat, pageIndex);

    g.dispose();

    /* In PSPrinterJob images are printed in device space
     * and therefore we need to set a device space clip.
     */
    psPrinterJob.setClip(savedTransform.createTransformedShape(savedClip));


    /* Scale the bounding rectangle by the scale transform.
     * Because the scaling transform has only x and y
     * scaling components it is equivalent to multiply
     * the x components of the bounding rectangle by
     * the x scaling factor and to multiply the y components
     * by the y scaling factor.
     */
    Rectangle2D.Float scaledBounds
            = new Rectangle2D.Float(
                    (float) (region.getX() * scaleX),
                    (float) (region.getY() * scaleY),
                    (float) (region.getWidth() * scaleX),
                    (float) (region.getHeight() * scaleY));


    /* Pull the raster data from the buffered image
     * and pass it along to PS.
     */
    ByteComponentRaster tile = (ByteComponentRaster)deepImage.getRaster();

    psPrinterJob.drawImageBGR(tile.getDataStorage(),
                        scaledBounds.x, scaledBounds.y,
                        scaledBounds.width,
                        scaledBounds.height,
                        0f, 0f,
                        deepImage.getWidth(), deepImage.getHeight(),
                        deepImage.getWidth(), deepImage.getHeight());


}
 
Example 19
public static void init() {
    pixelroot = new Group("pixel", "Pixel Access Benchmarks");

    pixeloptroot = new Group(pixelroot, "opts", "Pixel Access Options");
    doRenderTo = new Option.Toggle(pixeloptroot, "renderto",
                                   "Render to Image before test",
                                   Option.Toggle.Off);
    doRenderFrom = new Option.Toggle(pixeloptroot, "renderfrom",
                                     "Render from Image before test",
                                     Option.Toggle.Off);

    // BufferedImage Sources
    bufimgsrcroot = new Group.EnableSet(pixelroot, "src",
                                        "BufferedImage Sources");
    new BufImg(BufferedImage.TYPE_BYTE_BINARY, 1);
    new BufImg(BufferedImage.TYPE_BYTE_BINARY, 2);
    new BufImg(BufferedImage.TYPE_BYTE_BINARY, 4);
    new BufImg(BufferedImage.TYPE_BYTE_INDEXED);
    new BufImg(BufferedImage.TYPE_BYTE_GRAY);
    new BufImg(BufferedImage.TYPE_USHORT_555_RGB);
    new BufImg(BufferedImage.TYPE_USHORT_565_RGB);
    new BufImg(BufferedImage.TYPE_USHORT_GRAY);
    new BufImg(BufferedImage.TYPE_3BYTE_BGR);
    new BufImg(BufferedImage.TYPE_4BYTE_ABGR);
    new BufImg(BufferedImage.TYPE_INT_RGB);
    new BufImg(BufferedImage.TYPE_INT_BGR);
    new BufImg(BufferedImage.TYPE_INT_ARGB);

    // BufferedImage Tests
    bufimgtestroot = new Group(pixelroot, "bimgtests",
                               "BufferedImage Tests");
    new BufImgTest.GetRGB();
    new BufImgTest.SetRGB();

    // Raster Tests
    rastertestroot = new Group(pixelroot, "rastests",
                               "Raster Tests");
    new RasTest.GetDataElements();
    new RasTest.SetDataElements();
    new RasTest.GetPixel();
    new RasTest.SetPixel();

    // DataBuffer Tests
    dbtestroot = new Group(pixelroot, "dbtests",
                           "DataBuffer Tests");
    new DataBufTest.GetElem();
    new DataBufTest.SetElem();
}
 
Example 20
Source Project: poster-generater   File: Poster.java    License: MIT License 4 votes vote down vote up
/**
 * 绘制图片
 *
 * @return File
 * @throws IOException
 */
public File draw() throws IOException {
    // 初始化图片
    BufferedImage image = new BufferedImage(width, height, format.equals(Format.png) ? BufferedImage.TYPE_INT_ARGB : BufferedImage.TYPE_3BYTE_BGR);

    // create graphics
    Graphics2D gd = image.createGraphics();

    // 初始化画布层级 map
    Map<Integer, ArrayList<Drawable>> indexMap = new HashMap<>();
    ArrayList<Drawable> drawables;

    // 如果有背景,画个矩形做背景
    if (backgroundColor != null) {
        gd.setColor(ColorTools.String2Color(backgroundColor));
        gd.fillRect(0, 0, width, height);
    }

    if (this.blocks != null) {
        // 遍历 blocks
        for (Block block : this.blocks) {
            push2map(indexMap, block);
        }
    }

    if (this.lines != null) {
        // 遍历 lines
        for (Line line : this.lines) {
            push2map(indexMap, line);
        }
    }

    if (this.images != null) {
        // 遍历 images
        for (Image img : this.images) {
            push2map(indexMap, img);
        }
    }

    if (this.texts != null) {
        // 遍历 texts
        for (Text text : this.texts) {
            push2map(indexMap, text);
        }
    }

    // 按 index 顺序执行绘画过程
    for (Integer index : indexMap.keySet()) {
        drawables = indexMap.get(index);
        if (drawables != null) {
            for (Drawable drawable : drawables) {
                drawable.draw(gd, width, height);
            }
        }
    }

    gd.dispose();

    // 创建临时文件
    File file = File.createTempFile(this.key(), "." + format.toString());
    ImageIO.write(image, format.toString(), file); // 把文件写入图片
    file.deleteOnExit(); // 使用完后删除文件

    return file;
}