Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 5 of 5

Thread: Convert JFrame graphics into a jpeg file

  1. #1
    Junior Member
    Join Date
    Jun 2010
    Posts
    26
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Convert JFrame graphics into a jpeg file

    Hello everyone, I have had this problem for quite a while but never thought to come and ask on a forum. I just looked around because I thought it was a simple problem that required a key word in the coding or something. Turns out, I can't find any help anywhere.

    My problem is I want to turn a user specified graphic made in a simple JFrame program into a jpeg (or really any 'picture' format) but I don't know how. The way I have saved it is by saving the pixels in the pic into an array that is printed into a text file. So really, my jpeg file is a text file. This runs far too slow because I need to be able to load the pic several times in animations.

    Here is the code. It's a very simple, user size specified, black and white checkered pic that is saved into a text file to either be loaded or written over by a new pic the next time you run the program:

    /*Hello, welcome to SimplePic. This program:
     *	1. asks weather you want to create a new pic or load the last pic created.
     *	2. if you choose to make a new pic, it asks for the width and height in pixels
     *	3. the program then creates a checkered pic of the specified size (or loads the last pic you made) starting with a black pixel in the top left corner always.
     *To see the save file, look for a text file called 'picText.txt' in the same folder as this program. It will have 2 numbers for the first 2 lines (width then height),
     *and then it will have (if word wrap is turned off; it doesn't have to be) a square of letters ababab...representing the pixel array in this program.
     *
     *MY MAIN PROBLEM: I want to convert this text file/pic into a jpeg or some kind of picture file so that:
     *	1. a text file is not necessary
     *	2. the program loads the pic much faster like it was openning a pic you drew in microsoft paint.
     *I need this because I want to be able to create this pic, but then load it repeatedly in animations.
     *
     *Good luck and thank you.
     *-Ben 
    */
     
    //needed libraries
    import javax.swing.JFrame;
    import java.awt.*;
    import java.util.*;
    import java.io.*;
     
    public class SimplePic extends JFrame{
    	//variables
    	private Color c1 = new Color(0,0,0);//black
    	private Color c2 = new Color(255,255,255);//white
    	private char char1 = 'a';
    	private char char2 = 'b';
    	private char[][]pixels;
    	private int width,height;
    	private Container contents;
     
    	//new SimplePic
    	public SimplePic(int xsize,int ysize){
    		width=xsize;
    		height=ysize;
    		pixels=new char[xsize][ysize];
    		generatePic();
    		contents=getContentPane();
    		setSize(xsize,ysize);
    		setVisible(true);
    	}
     
    	//load SimplePic
    	public SimplePic(){
    		super("SimplePic");
    		loadPic("picText.txt");
    		contents=getContentPane();
    		setSize(width,height);
    		setVisible(true);
    	}
     
    	//generate Pic, creates a fine checkered pic based on remainders when dividing by 2
    	public void generatePic(){
    		for(int y=0;y<height;y++){//top to bottom
    			for(int x=0;x<width;x++){//left to right
    				//if x and y coordinate pixel has no remainder, set to black
    				if(x%2==0&&y%2==0){
    					pixels[x][y]=char1;
    				}
    				//if x coordinate pixel has a remainder of 1, but y does not, set to white	
    				if(x%2==1&&y%2==0){
    					pixels[x][y]=char2;
    				}
    				//if y coordinate pixel has a remainder of 1, but x does not, set to white
    				if(x%2==0&&y%2==1){
    					pixels[x][y]=char2;
    				}
    				//if x and y coordinate pixel has a remainder of 1, set to black
    				if(x%2==1&&y%2==1){
    					pixels[x][y]=char1;
    				}
    			}
    		}
    	}
     
    	//render pic
    	public void paint(Graphics g){
    		super.paint(g);
    		Color color=c1;
    		for(int y=0;y<height;y++){
    			for(int x=0;x<width;x++){
    				//convert char array to colors black and white
    				switch(pixels[x][y]){
    					case 'a':color=c1;break;
    					case 'b':color=c2;break;
    				}
    				g.setColor(color);
    				g.fillRect(x,y,1,1);
    			}
    		}
    	}
     
    	//main method
    	public static void main(String[]args){
    		//i did not bother making any code for input error checking, this is a bare bones example
    		Scanner scan=new Scanner(System.in);
    		System.out.println("new pic or load pic? (n or l)");
    		String choice=scan.nextLine();
    		char c=choice.charAt(0);
    		if(c=='n'){
    			System.out.println("please enter width of pic (int)");
    			int x=scan.nextInt();
    			System.out.println("please enter height of pic (int)");
    			int y=scan.nextInt();
    			SimplePic newPic=new SimplePic(x,y);
    			newPic.savePic("picText.txt");
    			newPic.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		}
    		if(c=='l'){
    			SimplePic loadPic=new SimplePic();
    			loadPic.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		}
     
    	}
     
    	//save current pic
    	public void savePic(String fn){
    		try{
    			PrintWriter out=new PrintWriter(new FileWriter(fn));
    			//the first 2 lines of the txt file are reserved for width and height
    			out.println(width);
    			out.println(height);
    			//turn word wrap off in the txt file to see a checkered square of letters representing the pixels array
    			for(int y=0;y<height;y++){
    				for(int x=0;x<width;x++){
    					out.print(pixels[x][y]);
    				}
    				out.println();
    			}
    			out.close();
    			System.out.println("Saved to "+fn);
    		}
    		catch(IOException e){System.out.println("Error saving to "+fn);}
    	}
     
    	//load previous pic
    	public void loadPic(String fn){
    		System.out.println("Reading "+fn+", loading...");
    		try{
    			BufferedReader br=new BufferedReader(new FileReader(fn));
    			String line;
    			char charLine[];
    			int numRows=0;
    			//read the first 2 lines of the txt file to get the width and height
    			String swidth=br.readLine();
    			String sheight=br.readLine();
    			width=Integer.parseInt(swidth);
    			height=Integer.parseInt(sheight);
    			//turn the square of letters in the txt file into the pixel array (turn word wrap off in the txt file to see more clearly)
    			pixels=new char[width][height];
    			while((line=br.readLine())!=null){
    				while(numRows<height){
    					charLine=line.toCharArray();
    			        int x=0;
    			        while((x<width)){
    			          	pixels[x][numRows]=charLine[x];
    			          	x++;
    		        	}
    		        	numRows++;
    		        	line=br.readLine();
    				}
    			}
    			br.close();
    		}
    		catch (IOException e){
    			System.out.println("Error reading maze plan from " + fn);
          		System.exit(0);
        	}
    	}
    }

    I think I made it as clear as possible, but if you have any questions, I'd be glad to answer them. I really need this answered.


  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,162
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Convert JFrame graphics into a jpeg file

    Have you looked at the ImageIO class?
    It will write images to files.
                        javax.imageio.ImageIO.write((BufferedImage)theImg, "PNG", imgFile);

  3. #3
    Junior Member
    Join Date
    Jun 2010
    Posts
    26
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Re: Convert JFrame graphics into a jpeg file

    Quote Originally Posted by Norm View Post
    Have you looked at the ImageIO class?
    It will write images to files.
                        javax.imageio.ImageIO.write((BufferedImage)theImg, "PNG", imgFile);
    So would I make a method to replace my savePic method and use ImageIO.write instead of FileWriter? could you give some sample code regarding ImageIO.write?

  4. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,162
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Convert JFrame graphics into a jpeg file

    give some sample code regarding ImageIO.write
    How about this:
                java.io.FileOutputStream fos  = new java.io.FileOutputStream(targetPath);
     
                //Create the pic..
                Image img = ((ImageIcon)lblImg.getIcon()).getImage();
                BufferedImage bi = new BufferedImage(
                        img.getWidth(null),
                        img.getHeight(null),
                        BufferedImage.TYPE_INT_RGB);
                Graphics2D g2 = bi.createGraphics();
                g2.drawImage(img, 0, 0, null);
     
                ImageIO.write(bi, "jpg", fos);
    Last edited by Norm; June 22nd, 2010 at 01:47 PM.

  5. The Following User Says Thank You to Norm For This Useful Post:

    Perd1t1on (June 22nd, 2010)

  6. #5
    Junior Member
    Join Date
    Jun 2010
    Posts
    26
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Re: Convert JFrame graphics into a jpeg file

    THANK YOU SIR!!!! I have no idea why this was so hard for me to find, but you pointed me in the right direction and I figured it out. I have been wandering around this site today a bit, and I have found you to be a regular helper, so I'm guessing you are probably quite experienced. However, if you are unable to get a question solved and it regards general logic or arrays, I would be glad to help. Just send a message. Syntax is my problem, but I think I'm pretty good with logic, I figured things out my teacher couldn't. I'm not bragging, seriously if you need help in those 2 areas, I think I may be of some assistance.

Similar Threads

  1. How to Convert DWG File to an Image
    By lance9200 in forum Java Theory & Questions
    Replies: 0
    Last Post: June 17th, 2010, 10:21 AM
  2. graphics in job?
    By SweetyStacey in forum The Cafe
    Replies: 10
    Last Post: May 3rd, 2010, 03:29 PM
  3. How do i use graphics with Java?
    By DarrenReeder in forum Java Theory & Questions
    Replies: 4
    Last Post: December 27th, 2009, 05:16 PM
  4. Increasing performance of my graphics routines
    By willberg in forum AWT / Java Swing
    Replies: 6
    Last Post: November 16th, 2009, 01:41 PM
  5. Simple graphics practice on previous Java code
    By amrawad_85 in forum AWT / Java Swing
    Replies: 5
    Last Post: June 19th, 2009, 10:30 AM