Salvar um grafico em jpg

6 respostas
kaberdock

eu to precisando criar transformar um objeto de uma classe que cria um grafico em uma imagem.. ai vai a classe

import java.awt.Color;

import java.awt.GradientPaint;

import java.awt.Graphics2D;

import java.awt.geom.Line2D;

import java.awt.geom.Rectangle2D;



import br.uems.sead.model.statistics.continuous.AbsFreqDistribution;

import br.uems.sead.model.statistics.continuous.FreqDistribution;

import br.uems.sead.view.util.StringManager;



/**

 * A classe <code>Histogram</code> representa um gráfico de histograma de uma

 * distribuição de frequência.

 * 

 * @author Jefersson Alex dos Santos

 */

public class Histogram extends Graphic {

    

    /**

     * Armazena a escala de valores a ser utilizada no eixo Y.

     */

    private float scaleY;



    /**

     * Armazena a largura de cada barra do Gráfico.

     */

    private int barWidth;



    public Histogram(AbsFreqDistribution d) {

        super(d);

    }



    public void paintX(Graphics2D g) {

        //		double init = d.getInitialValue() - d.getH();

        double init = d.getLi(0) - 2 * d.getH();

        init = math.roundUnits(init + d.getH(), d.getDecUn());

        barWidth = getAmplitudeFreq();



        int x = 0;

        for (int i = 0; i < d.getClassCount() + 3; i++) {

            g.draw(new Line2D.Float(x, -2, x, 2));

            g.fill(StringManager.stringShape("" + init, fonte, g, x, 15,

                    StringManager.CENTER));

            x += barWidth;

            init = math.roundUnits(init + d.getH(), d.getDecUn());

        }

        g.draw(new Line2D.Float(0, 0, x - barWidth, 0));

    }



    /**

     * Desenha o gráfico de barras da distribuição

     */

    public void paintGraphic(Graphics2D g) {

        scaleY = getScaleY();

        barWidth = getAmplitudeFreq();



        int x = 0;

        int y = 0;



        for (int i = 1; i < d.getClassCount() + 1; i++) {

            x = barWidth * i;

            y = (int) (scaleY * (Integer)d.get(i - 1));



            g.setPaint(new GradientPaint(x, -y, Color.BLUE, x, 0, new Color(0,

                    0, 100)));



            g.fill(new Rectangle2D.Float(x, -y, barWidth, y));

            g.setPaint(Color.black);

            g.draw(new Rectangle2D.Float(x, -y, barWidth, y));

        }

    }

}

ja vasculhei a documentação do java e naun achei nada, ou achei e não soube

6 Respostas

fabiofalci

Um conselho antes, use java2d double buffered. Não olhei se o teu código faz isso… se não fizer faça.

Agora, com o Graphics e o Image na mão, olhe esse código exemplo que grava numa figura.

public class Java2DTest2 extends JPanel {

	private Graphics buffer;

	private BufferedImage offscreen;

	public Java2DTest2() {
		this.offscreen = new BufferedImage(800, 600, 1);
		this.buffer = this.offscreen.getGraphics();
		this.setPreferredSize(new Dimension(800, 600));
	}

	@Override
	public void paint(Graphics g) {
		this.buffer.setColor(Color.WHITE);
		this.buffer.fillRect(0, 0, 800, 600);

		this.buffer.setColor(Color.BLACK);
		this.buffer.drawString("Double-buffered", 10, 10);

		this.buffer.setColor(Color.BLUE);
		this.buffer.fillOval(200, 150, 100, 50);

		g.drawImage(this.offscreen, 0, 0, this);

		try {
			ImageIO.write(offscreen, "png", new File("/tmp/mypng.png"));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void update(Graphics g) {
		paint(g);
	}

	public static void main(String[] args) {
		JFrame frame = new JFrame();
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setContentPane(new JScrollPane(new Java2DTest2()));
		frame.setSize(400, 300);
		frame.setVisible(true);
	}
}

A linha 27 grava a imagem.

Uma alternativa é usar esse código que tira uma figura da tela toda, talvez se tu trabalhar nas coordenadas tu consiga
tirar só o que tu quiser.

public static void captureFrame(JFrame frame, String fileName)
		throws Exception {
	Dimension screenSize = java.awt.Toolkit.getDefaultToolkit()
			.getScreenSize();
	Rectangle screenRectangle = new Rectangle(screenSize);
	Robot robot = new Robot();
	BufferedImage image = robot.createScreenCapture(screenRectangle);
	// Point p = MouseInfo.getPointerInfo().getLocation();
	// Graphics2D g2d = image.createGraphics();
	// g2d.setColor(Color.BLACK);
	// g2d.fillRect(p.x, p.y, 30, 30);
	ImageIO.write(image, "png", new File(fileName));
}

Testa ai!

kaberdock

valeu vo testar

kaberdock

cara isso seria para um objeto tipo graphics(drawImage()) certo? mas no meu caso eh graphics2d , aqui ta salvando uma tela preta

fabiofalci

Cara, nao tem problema, pode fazer um cast para Graphics2D no meu exemplo, vai funcionar.

Vc está usando double buffered?

Pq o que é desenhado na figura é um BufferedImage que está ‘associado’ a um Graphics.
Este Graphics que vc deve usar para desenhar.

Coloca ai o teu exemplo modificado…

kaberdock
public void paintGraphic(Graphics2D g) {
        scaleY = getScaleY();
        barWidth = getAmplitudeFreq();

        int x = 0;
        int y = 0;

        for (int i = 1; i < d.getClassCount() + 1; i++) {
            x = barWidth * i;
            y = (int) (scaleY * (Integer)d.get(i - 1));

            g.setPaint(new GradientPaint(x, -y, Color.BLUE, x, 0, new Color(0,
                    0, 100)));

            g.fill(new Rectangle2D.Float(x, -y, barWidth, y));
            g.setPaint(Color.black);
            g.draw(new Rectangle2D.Float(x, -y, barWidth, y));
            
        }
        	
        	g = (Graphics2D) image.getGraphics();
        	g.drawImage(image,0,0,this);
    		try {  
     	       ImageIO.write( this.image, "png", new File("/tmp/mypng.png"));  
     	         } catch (IOException e) {  
     	             e.printStackTrace();  
     	        }  
        	
    }
}
ta ai
fabiofalci

Cara, acho que tu esta invertendo um pouco a ordem.

Esse image saiu da onde? Ele está sobreescrevendo o Graphics.

Lá no teu JPanel, no método paint, vc deve usar o double buffered.
Ou seja, cria um image e um Graphics a partir dele. No meu
exemplo é o tal do buffer.

Então faça todo o teu desenho no buffer. Ao final grave a imagem em disco
e desenhe ela no Graphics que o paint recebeu!

Criado 23 de março de 2009
Ultima resposta 24 de mar. de 2009
Respostas 6
Participantes 2