Hello guys,
I have a project to save an image from canvas to file.
I have tried googling for 3 days and nothing works.
Can anybody show me how to do it.
I have search from this forum and this is what i get.

http://www.daniweb.com/software-development/java/threads/436548/saving-canvas-as-image
" Create a new buffered image. Get its Graphics. Draw your canvas on the Graphics. (Use your existing paintComponent method and pass the BufferedImage's Graphics to it.) "

well i dont realy understand how to code it. Please give me an example how it should be done.
Thanks.

Hi Lius.

The purpose of your project is for you to learn and practice Java programming, not Googling.

The only way to understand how to code this is to start at the beginning and solve each problem as you encounter it. We will help with that.

You have a short step-by-step approach described in the post you quoted. Use that as a template and start at the beginning.
If/when you get stuck post what you have done so far and explain what's blocking you.

ps: DaniWeb Member Rules (which you agreed to when you signed up) include:
"Do provide evidence of having done some work yourself if posting questions from school or work assignments"
http://www.daniweb.com/community/rules

Here what have i done so far,

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package javaproc;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Arrays;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Lius
 */
public class MainFrame extends javax.swing.JFrame {
    File file;
    BufferedImage[] processedImage;
    GCanvas canvas = new GCanvas();

    /**
     * Creates new form MainFrame
     */
    public MainFrame() {
        initComponents();
        canvas.setSize(300, 300);
        Dimension size = new Dimension(300,300);  
        canvas.setPreferredSize(size);
        panelGen.add(canvas);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jFileChooser1 = new javax.swing.JFileChooser();
        jLabel1 = new javax.swing.JLabel();
        btnOpen = new javax.swing.JButton();
        picSource = new javax.swing.JLabel();
        panelGen = new javax.swing.JPanel();
        btnGen = new javax.swing.JButton();
        btnSave = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setText("Image Source");

        btnOpen.setText("Open");
        btnOpen.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnOpenActionPerformed(evt);
            }
        });

        picSource.setToolTipText("");
        picSource.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));

        javax.swing.GroupLayout panelGenLayout = new javax.swing.GroupLayout(panelGen);
        panelGen.setLayout(panelGenLayout);
        panelGenLayout.setHorizontalGroup(
            panelGenLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 320, Short.MAX_VALUE)
        );
        panelGenLayout.setVerticalGroup(
            panelGenLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 0, Short.MAX_VALUE)
        );

        btnGen.setText("Gen");
        btnGen.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnGenActionPerformed(evt);
            }
        });

        btnSave.setText("Save");
        btnSave.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSaveActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addGap(18, 18, 18)
                        .addComponent(btnOpen)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnGen)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnSave))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(picSource, javax.swing.GroupLayout.PREFERRED_SIZE, 300, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(panelGen, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(475, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(btnOpen)
                    .addComponent(btnGen)
                    .addComponent(btnSave))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(picSource, javax.swing.GroupLayout.DEFAULT_SIZE, 300, Short.MAX_VALUE)
                    .addComponent(panelGen, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap(372, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>                        

    private void btnOpenActionPerformed(java.awt.event.ActionEvent evt) {                                        

        int returnVal = jFileChooser1.showOpenDialog(this);

        if (returnVal == jFileChooser1.APPROVE_OPTION) {
            file = jFileChooser1.getSelectedFile();
            //This is where a real application would open the file.
            //log.append("Opening: " + file.getName() + "." + newline);
          picSource.setIcon(new javax.swing.ImageIcon(file.getAbsolutePath())); 
            try {
                crop();
            } catch (Exception ex) {
                Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
            }
        } 
    }                                       

    private void btnGenActionPerformed(java.awt.event.ActionEvent evt) {                                       
       try {
           crop();
       } catch (Exception ex) {
           Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
       } 
    }                                      

    private void btnSaveActionPerformed(java.awt.event.ActionEvent evt) {                                        
        save();
    }                                       

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new MainFrame().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify                     
    private javax.swing.JButton btnGen;
    private javax.swing.JButton btnOpen;
    private javax.swing.JButton btnSave;
    private javax.swing.JFileChooser jFileChooser1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel panelGen;
    private javax.swing.JLabel picSource;
    // End of variables declaration                   

    private void crop() throws Exception {
        ImageCropper c = new ImageCropper(file.getAbsoluteFile());
        //crop int 90 pieces;
        int l=0;
        int width=30;
        int length=30;
        int jPieces=100;
        int loopj=10;
        int loopi=10;

        processedImage = new BufferedImage[jPieces];
        for(int i=0;i<loopi;i++){
            for(int j=0;j<loopj;j++){
                c.cropImage(width, length, i*width, j*length);
                processedImage[l] = c.getCrop();
                l++;
            }
        }
        int[] r=new int[jPieces];
        int rand =0;
        for(int i=0;i<r.length;i++){
            rand = (int) (Math.random() * ( r.length));
            if(Arrays.binarySearch(r, 0, r.length, rand)<=-1)
                r[i]= rand;
        }
        l = 0;
        for(int i=0;i<loopi;i++){
            for(int j=0;j<loopj;j++){
                drawtoCanvas(processedImage[r[l]],i*width, j*length);
                l++;
            }
        }


    }

    private void drawtoCanvas(BufferedImage processedImage, int x, int y) {
        Graphics g2d = canvas.getGraphics();
        canvas.paint(g2d,processedImage,x,y);

    }

    private void save() {


        int r = jFileChooser1.showSaveDialog(this);
        File file2 = null; 
        if(r == jFileChooser1.APPROVE_OPTION){
        try {
            file2 = jFileChooser1.getSelectedFile();
            BufferedImage bi = ScreenImage.createImage(canvas);
            ScreenImage.writeImage(bi, file2.getAbsolutePath());
        } catch (Exception ex) {
            System.out.println("Error saving");
        }
        }
    }

class GCanvas extends Canvas
{
  public void paint(Graphics g,BufferedImage g2, int x,int y)
  {
    Graphics2D g2d = (Graphics2D)g;
    g2d.drawImage(g2,x,y,this);
  }
}
}

Well i just making a personal project, thats all. hehe..
the idea is to import a picture than crop it for n small picture, than join
it again at canvas randomly. And i am stuck at saving it to a image file at save () method. Please help me. thanks.

Right now i use sreenimage for saving, but the output is little bullry, so i need other solution

yesterday i tried use jlabel still confused how to update the imageicon not to redraw it on my code.

for(int i=0;i<loopi;i++){
            for(int j=0;j<loopj;j++){
                drawtoCanvas(processedImage[r[l]],i*width, j*length);
                l++;
            }
        }

this will looping all bufferedimage to that jlabel, what i need now is how to update the image of the imageicon on jlabel,so all pieces will be drawn as one complete image again.. something to do with the paint method..

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.