简体   繁体   中英

Creating a PNG image using an array of points in Java (Always comes up black)

I currently have a one-dimensional double array holding 50 different points meant to be spaced 1 apart. I need these points to be drawn and connected by lines in an image. Currently the PNG image is being produced, and if I add in an individual line it will work, but somehow the loop makes the entire image come up as black. Any ideas on what's going wrong?

BufferedImage bi = new BufferedImage(50, 50, BufferedImage.TYPE_INT_ARGB);

    Graphics2D ig2 = bi.createGraphics();
    ig2.setBackground(Color.white);
    ig2.setColor(Color.red);

    for(int i = 0; i < 49; i++){

        Shape line = new Line2D.Double(i,finalpoints[i],i+1,finalpoints[i+1]);
        ig2.draw(line);

    }

    //Export the result to a file
    try {
        ImageIO.write(bi, "PNG", new File("C://Users/vince/Desktop/heightmap.png"));
    } catch (IOException e) {
        System.out.println("There was an error writing the image to file");

    }

There is two overloaded Line2D.Double constructors: the 1st one takes two Point2D as parameters so if your array contains Point2D objects your code should be :

 Shape line = new Line2D.Double(finalpoints[i],finalpoints[i+1]);

the second method Line2D.Double(double x1, double y1, double x2, double y2) and it takes the points' coordinates, so if you want the second, tour code should be like this:

Shape line = new Line2D.Double(finalpoints[i].getX(), finalpoints[i].getY(), finalpoints[i+1].getX(), finalpoints[i+1].getY());

if your array doesn't contain Point2D objects, just update your post so we can help you.

Setting the foreground color does not fill the background. Also a Graphics.dispose() is needed.

BufferedImage bi = new BufferedImage(50, 50, BufferedImage.TYPE_INT_ARGB);

Graphics2D ig2 = bi.createGraphics();
ig2.setBackground(Color.white);
ig2.setColor(Color.white);
ig2.fillRect(0, 0, 50, 50);
ig2.setColor(Color.red);

// Better use a ig2.drawPolyline (Polygon) so the joints are nicer.
for(int i = 0; i < 49; i++){

    Shape line = new Line2D.Double(i,finalpoints[i],i+1,finalpoints[i+1]);
    ig2.draw(line);

}
ig2.dispose();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM