Saving canvas as an image: embedded in an applet

hi everyone,
I'm trying to save shapes I've drawn in a canvas as a jpg. This works, thanks to a solution I found somewhere in one of these forums. However, I need to embed the application in an applet, and in that case it doesn't work anyone. Here is some code that works when I don't use applets:
public class MenuItemHandler implements ActionListener{
          public void actionPerformed(ActionEvent e) {
               try{
                    FileDialog fd = new FileDialog(new Frame(), "Save as JPG", FileDialog.SAVE);
          fd.setFile("canvas.jpg");
          fd.setVisible(true);
          String name = fd.getDirectory() + fd.getFile();
          File file = new File(name);
                    ImageUtils utils = new ImageUtils();
                    BufferedImage image = utils.createComponentImage(tc);
                    utils.encodeImage(image,file);
               catch(Exception ex) {
                    ex.printStackTrace(); }
     class ImageUtils {
          private JPEGImageEncoder encoder = null;
          private FileOutputStream fileStream = null;
          public BufferedImage createComponentImage(Component component){
               BufferedImage image = (BufferedImage)component.createImage(component.getWidth(),component.getHeight());
               Graphics graphics = image.getGraphics();
               if(graphics != null) { component.paintAll(graphics); }
               return image;
          public void encodeImage(BufferedImage image, File file) throws IOException{
               fileStream = new FileOutputStream(file);
               JPEGEncodeParam encodeParam = JPEGCodec.getDefaultJPEGEncodeParam(image);
               encoder = JPEGCodec.createJPEGEncoder(fileStream);
               encoder.encode(image,encodeParam);
               fileStream.close();
When the code is embedded in an applet, I see my appliaction and I get my save dialog box, but there won't be written any file anymore. I suppose it has something to do with the fact that I don't use getDocumentBase() or getCodeBase(), but I'm not sure about that, and if this is the reason, I don't know exactly how to implement it in the code.
I hope that someone can help me!!
Thanks in advance!

hi everyone,
I'm trying to save shapes I've drawn in a canvas as a jpg. This works, thanks to a solution I found somewhere in one of these forums. However, I need to embed the application in an applet, and in that case it doesn't work anyone. Here is some code that works when I don't use applets:
public class MenuItemHandler implements ActionListener{
          public void actionPerformed(ActionEvent e) {
               try{
                    FileDialog fd = new FileDialog(new Frame(), "Save as JPG", FileDialog.SAVE);
          fd.setFile("canvas.jpg");
          fd.setVisible(true);
          String name = fd.getDirectory() + fd.getFile();
          File file = new File(name);
                    ImageUtils utils = new ImageUtils();
                    BufferedImage image = utils.createComponentImage(tc);
                    utils.encodeImage(image,file);
               catch(Exception ex) {
                    ex.printStackTrace(); }
     class ImageUtils {
          private JPEGImageEncoder encoder = null;
          private FileOutputStream fileStream = null;
          public BufferedImage createComponentImage(Component component){
               BufferedImage image = (BufferedImage)component.createImage(component.getWidth(),component.getHeight());
               Graphics graphics = image.getGraphics();
               if(graphics != null) { component.paintAll(graphics); }
               return image;
          public void encodeImage(BufferedImage image, File file) throws IOException{
               fileStream = new FileOutputStream(file);
               JPEGEncodeParam encodeParam = JPEGCodec.getDefaultJPEGEncodeParam(image);
               encoder = JPEGCodec.createJPEGEncoder(fileStream);
               encoder.encode(image,encodeParam);
               fileStream.close();
When the code is embedded in an applet, I see my appliaction and I get my save dialog box, but there won't be written any file anymore. I suppose it has something to do with the fact that I don't use getDocumentBase() or getCodeBase(), but I'm not sure about that, and if this is the reason, I don't know exactly how to implement it in the code.
I hope that someone can help me!!
Thanks in advance!

Similar Messages

  • How can I drag an image from a page in Safari to the finder and have it be saved as an *actual* image instead of a webloc?

    Safari used to let me drag an image from a webpage to the finder and have the dragged file be saved as an actual image but now all that's saved is a webloc file.  I want the image saved, not a reference to the image's URL - do I now have to always use "save as" to save it?
    I can understand Safari creating a webloc file if I dragged the site icon from the location bar to the finder, but to make the default behavior for dragging things that are parts of a page (not the page itself) as webloc files seems like a HUGE step backwards for usability.
    Does anyone know if there's, say, a key to hold when dragging to avoid saving a webloc file or a defaults command or something to make Safari revert back to sane draging behavior?

    Good questions...  I'll have to try and figure out when the problem first happened - I was thinking it was when I upgraded to Safari 5.1.4 but that might not be the case...  I'll try your suggestions to see if any of them eliminate the problem (I have restarted recenlty and that didn't fix it) but I'll try repairing permissions,etc.  Thanks!
    hmmm... Mcbuffy: are you implying that you *don't* get the webloc when dragging an image out of Safari and that this isn't a caused by change to Safari but is a big/conflict in mine?

  • Send html email with image embedded

    Hi Guys,
    I want send an email using class CL_BCS.
    Can someone please help me to tell me how can we send the email with image embedded in the body?
    The image is stored in the mime repository and was uploaded through se78.
    I have searched online but am not able to send it.
    It will be great if someone has working code for this.
    Regards,
    Dhruv Kashyap

    Hi go to T-code : SMW0   -- To upload the images , after that you can find that entries in wwwparams table .
    Refer this .
    **************** - Display images (like company logo) on the selection-screen
    In order to send it as email you have to add  attachment type as BMP from you BCS class.
    Just try you can .

  • Saving PDF files as image files using the Preview application

    I'm converting PDF files into image files for use with OCR software. The problem is that changing the pixels/inch option from 150 to say 300 does not improve the resolution of the resulting image file. E.g. if I save at 150 p/i and then 300p/i both image files are the same size and resolution. I've tried JPG, JPG-2000, TIFF, and GIF. All produce the same fuzzy result. What am I doing wrong?

    The schematic file is made up from vector graphics. There are no images embedded in it. For some reason the OCR software (PDF pen) will not recognize the vector drawn characters near the various components. e.g. There may be a resistor with "R5" written next to it. This is the resistors designator. The designator is what I am trying to do the search on. Since PDF pen can perform OCR on scanned (image) documents I thought that turning the PDF schematic into an image file e.g. JPG using Preview would do the trick. Unfortunately as I have already mentioned I can not seem to get Preview to improve the resolution on the resulting image file - the OCR software struggles to recognize any print.

  • Retrieving Images Embedded In XML (from rss using xsl)

    I am trying to comsuem and rss feed into my site but i dont seem to see an "image" element in the Item node. can someoen tell me how to retrieve Images Embedded In XML dreamwaever. i am using an xsl fragment on a pap server.
    Doh

    Hi there, I am using a jsp page that takes a xml page from the internet (user defines what page it is) it then takes the xsl feed and transforms the xml with a TransformerFactory object to get the results as an html page, the error is received when the jsp page is called
    Ian

  • Preview "this layered Photoshop file was not saved with a composite image" error message?

    hi, i get this message:
    in preview, when i try to open a .psd file by double-clicking it:
    "this layered Photoshop file was not saved with a composite image"
    is there any program that will open this file, that came with my new iMac?
    OS 10.9.5
    thanks!
    ps. when i clicked all through help on my Mac, it would not tell me what i needed to know.
    So, is this forum the best way to find actual useful info?

    Thank you Chris,for the correct  answer - Best, Bob

  • When saving iDVD to disk image the following message appears: "Error during rendering/codification. There was an error during rendering/codification of menus/slide presentation. The recording process was canceled.

    When saving iDVD to disk image the following message appears: "Error during rendering/codification. There was an error during rendering/codification of menus/slide presentation. The recording process was canceled.
    What am I doing wrong?

    Read and answer the questions posted by Bengt Wärleby in this thread: Cant burn my idvd project to...: Apple Support Communities
    OT

  • How do images embeded in InDesign link when using Creative Cloud on more than two desktops?

    How do images embeded in InDesign link when using Creative Cloud on more than two desktops?

    If I am understanding your question correctly, you shouldn't have to worry about embedded images in InDesign. Once embedded, the image is stored within the file.
    If you are wondering about linked images... InDesign will follow the path on your computer and, if it does not find the image, you will recieve a notification. Edit: To prevent this, I would suggest packaging your file using File > Package... This will create a folder with all of your fonts and linked graphics so that you need not worry about broken links.  I just remembered that you cannot upload folders directly to Creative Cloud so a packaged folder wouldn't be very helpful unless you wanted to upload each file manually.
    The best solution I see right now is to either embed the graphics in the document, or upload the images with your document to relink.
    I hope this helped,
    Michael

  • Create Image from Stream in Applet via Servlet

    First of all, I apologize if this isn't posted to the proper forum, as I am dealing with several topics here. I think this is more of an Image and I/O problem than Applet/Servlet problem, so I thought this forum would be most appropriate. It's funny...I've been developing Java for over 4 years and this is my first post to the forums! :D
    The problem is I need to retrieve a map image (JPEG, GIF, etc) from an Open GIS Consortium (OGC) Web Map Server (WMS) and display that image in an OpenMap Applet as a layer. Due to the security constraints on Applets (e.g., can't connect to a server other than that from which it originated), I obviously just can't have the Applet create an ImageIcon from a URL. The OpenMap applet will need to connect to many remote WMS compliant servers.
    The first solution I devised is for the applet to pass the String URL to a servlet as a parameter, the servlet will then instantiate the URL and also create the ImageIcon. Then, I pass the ImageIcon back to the Applet as a serialized object. That works fine...no problems there.
    The second solution that I wanted to try was to come up with a more generic and reusable approach, in which I could pass a URL to a servlet, and simply return a stream, and allow the applet to process that stream as it needs, assuming it would know what it was getting from that URL. This would be more usable than the specific approach of only allowing ImageIcon retrieval. I suppose this is actually more of a proxy. The problem is that the first few "lines" of the image are fine (the first array of buffered bytes, it seems) but the rest is garbled and pixelated, and I don't know why. Moreover, the corruption of the image differs every time I query the server.
    Here are the relevant code snippets:
    =====================Servlet====================
        /* Get the URL String from the request parameters; This is a WMS
         * HTTP request such as follows:
         * http://www.geographynetwork.com/servlet/com.esri.wms.Esrimap?
         *      VERSION=1.1.0&REQUEST=GetMap&SRS=EPSG:4326&
         *      BBOX=-111.11361,3.5885315,-48.345818,71.141304&
         *      HEIGHT=480&...more params...
         * It returns an image (JPEG, JPG, GIF, etc.)
        String urlString =
            URLDecoder.decode(request.getParameter("wmsServer"),
                              "UTF-8");
        URL url = new URL(urlString);
        log("Request parameter: wmsServer = " + urlString);
        //Open and instantiate the streams
        InputStream urlInputStream = url.openStream();
        BufferedInputStream bis = new
            BufferedInputStream(urlInputStream);
        BufferedOutputStream bos = new
            BufferedOutputStream(response.getOutputStream());
        //Read the bytes from the in-stream, and immediately write them
        //out to the out-stream
        int read = 0;
        byte[] buffer = new byte[1024];
        while((read = bis.read(buffer, 0, buffer.length)) != -1) {
            bos.write(buffer, 0, buffer.length);
        //Flush and close
        bos.flush();
        urlInputStream.close();
        bis.close();
        bos.close();
        .=====================Applet=====================
        //Connect to the Servlet
        URLConnection conn = url.openConnection();
        conn.setUseCaches(false);
        conn.setRequestProperty("header", "value");
        conn.setDoOutput(true);
        //Write the encoded WMS HTTP request
        BufferedWriter out =
            new BufferedWriter( new OutputStreamWriter(
                conn.getOutputStream() ) );
        out.write("wmsServer=" + URLEncoder.encode(urlString, "UTF-8"));
        out.flush();
        out.close();
        //Setup the streams to process the servlet response
        BufferedInputStream bis = new
            BufferedInputStream(conn.getInputStream());
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        //Read the bytes and immediately write to the out-stream
        int read = 0;
        byte[] buffer = new byte[1024];
        while((read = bis.read(buffer, 0, buffer.length)) != -1) {
            bos.write(buffer, 0, buffer.length);
        //Flush and close
        bis.close();</code>
        bos.flush();</code>
        byte[] imageBytes = bos.toByteArray();
        //Create the Image/ImageIcon
        Toolkit tk = Toolkit.getDefaultToolkit();
        Image image = tk.createImage(imageBytes);
        imageIcon = new ImageIcon(image);
        Could this be an offset problem in my buffers? Is there some sort of encoding/decoding I am missing somewhere?
    Thanks!
    Ben

    Without having a probing look, I was wondering why you do the following...
    while((read = bis.read(buffer, 0, buffer.length)) != -1) {
    bos.write(buffer, 0, buffer.length);
    while((read = bis.read(buffer, 0, buffer.length)) != -1) {
    bos.write(buffer, 0, buffer.length);
    }Your int 'read' holds the number of bytes read in but you then specify buffer.length in your write methods?!? why not use read? otherwise you will be writing the end of the buffer to your stream which contains random memory addresses. I think thats right anyway...
    Rob.

  • How draw image into frame in applet

    How draw image into frame in applet.Please give my simple example code.

    http://search.java.sun.com/search/java/index.jsp?qt=%2Bdraw+%2Bimage+%2Bpanel+%2Bhow&nh=10&qp=&rf=1&since=&country=&language=&charset=&variant=&col=javaforums

  • How can I upload a (image) file through an applet ?

    How can I upload a (image) file through an applet ?

    have a look at http://www.haller-systemservice.net/jupload/
    i'm using Apache Jakarta HTTPClient to create a new HTTP connection to the webserver and sending a new POST request, which holds the image file. (So it's RFC1867 conform)
    there is also an open source implementation of such an applet on sourceforge. it's also called JUpload, but i think it's not maintained any more.

  • Prob in saving canvas to jpg

    hi friends, i m tryin to save canvas to jpg n has de code for it but saved jpg file contalins black background... i hav attached de code.. can u plz execute it n suggest wat de prob is.....import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.BufferedImage;
    import java.io.*;
    import javax.imageio.ImageIO;
    public class CanvasClip extends Canvas implements ActionListener
        Rectangle clip;
        boolean showClip;
        public CanvasClip()
            clip = new Rectangle(50, 150, 350, 300);
            showClip = false;
        public void paint(Graphics g)
    System.out.println("inside");
            super.paint(g);
            Graphics2D g2 = (Graphics2D)g;
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                RenderingHints.VALUE_ANTIALIAS_ON);
            int w = getWidth();
            int h = getHeight();
            int dia = Math.min(w,h)/4;
            g2.setPaint(getBackground());
            g2.fillRect(0,0,w,h);
            g2.setPaint(Color.blue);
            g2.drawRect(w/16, h/16, w*7/8, h*7/8);
            g2.setPaint(Color.red);
            g2.fillOval(w/8, h/12, w*3/4, h*5/6);
            g2.setPaint(Color.green.darker());
            g2.fillOval(w/2-dia/2, h/2-dia/2, dia, dia);
            g2.setPaint(Color.orange);
            g2.drawLine(w/16+1, h/16+1, w*15/16-1, h*15/16-1);
            if(showClip)
                g2.setPaint(Color.magenta);
                g2.draw(clip);
        public void actionPerformed(ActionEvent e)
            Button button = (Button)e.getSource();
            String ac = button.getActionCommand();
            if(ac.equals("show"))
                showClip = !showClip;
                repaint();
            if(ac.equals("save"))
                save();
        private void save()
            int w = clip.width;
            int h = clip.height;
            BufferedImage img = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
            Graphics2D g2 = img.createGraphics();
            g2.translate(-clip.x, -clip.y);
            paint(g2);
            g2.dispose();
            String ext = "jpg";  // or "png"; "bmp" okay in j2se 1.5
            try
                ImageIO.write(img, "jpg", new File("canvasClip.jpg"));
            catch(IOException ioe)
                System.err.println("write error: " + ioe.getMessage());
        private Panel getUIPanel()
            Button show = new Button("show clip");
            Button save = new Button("save");
            show.setActionCommand("show");
            save.setActionCommand("save");
            show.addActionListener(this);
            save.addActionListener(this);
            Panel panel = new Panel();
            panel.add(show);
            panel.add(save);
            return panel;
        public static void main(String[] args)
            CanvasClip cc = new CanvasClip();
            Frame f = new Frame();
            f.addWindowListener(new WindowAdapter()
                public void windowClosing(WindowEvent e)
                    System.exit(0);
            f.add(cc);
            f.add(cc.getUIPanel(), "South");
            f.setSize(400,400);
            f.setLocation(200,200);
            f.setVisible(true);
    }I beleive u can get de wat prob is... if not ask me to b more clear

    Hi philihop,
    Firstly, thanks for your code and it helps me do my job.
    Please read the following words if you haven't solved this problem.
    Canvas paint method use Graphics object 'g' to draw something in the canvas. Its default value is black when you output to JPG image. That is the reason why it prints black background on jpg image. So please just add
    int width = getWidth();
    int height = getHeight();
    g.setColor(Color.white);
    g.fillRect(0, 0, width, height);
    This 4 lines code draw the whole display area in Color.white. And problem is solved.
    Byron
    Message was edited by: Byron on 29/01/2007
    byronzh

  • A few questions about Canvas and other Image related stuff.

    I am just starting to play around with Canvas in the hopes of using it to make a little game (not an applet) in my spare time. I have gotten a ball to bounce around the screen and switch colors when it bounces without too much work. (hooray for me!).
    I was wondering:
    1) If you always have to repaint the whole area of the canvas, or can you repaint sections of the screen?
    2) Can there only be one canvas per frame, or if you can have more, like say, one for each sprite (I tried in my own simplistic way but the second canvas overrode the first when I added it to the frame) or do you have to lay out all the sprites in one canvas every time before you paint?
    3) Is Canvas the best platform for rendering my animations and doing collision detection, or are other ways of presenting the images better? By better I mean lower usage of resources, higher speed, accessibility of events that occur. (I have read in the mindprod java glossary "[Canvas] receives all the raw mousing events. Panels, in contrast, see only a few.")
    4) In a call to paint which tells it to display some images which are much larger than the frame the canvas is in, is time and effort spent working on those pixels that aren't displayed or does it take about the same amount of resources as for images that fit in the frame since the same amount of picture is actually displayed?
    5) Is there any convenient way to layers with canvas besides just controlling the order in which the images are painted. (I will admit I haven't searched for this information yet, because I just thought about it.)
    6) Is there any other information you guys would care to bestow on me?
    If any of this question is ridiculous, obvious, ignorant or any other negative adjective, then I apologize. I will continue messing around in the meantime.
    Thanks
    --John                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    Okay, well I got it to work by drawing them both to the same canvas. duh I guess.
    Can you have more than one canvas in a frame? How do you set the size if so.
    How do I implement the z-order? I thought of doing it manually by sending the paint method a list of objects to paint and manually managing the order of that list. Would that be an acceptable way to do it?
    Should I only be trying to paint to one canvas? What I would like to do is have several canvases with transparent backgrounds so that I can draw different layers in the same frame. That way flying stuff would be painted on a different canvas than stuff on the ground, and then putting it all in a frame would tie the pictures together into a scene. Kind of like how they do distance in animation by having different layers of drawings on clear plastic that they can move at different speeds to give the illusion of depth.
    Any advise? Sorry for the douba-post
    Thanks
    --John                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • Saving a series of images (from a smart camera) into an AVI file

    Hello,
    I have a lab setup in which we view brain cell deflections in a well-plate after being pressurized with air for 50ms. I have a smart camera hooked up to an IMAQ PCI card to acquire images.
    I'm trying to save the series of images into an avi file, so that I can view the deflections in a slow video.
    The way I have it set up at the moment takes an image and saves it in an avi pre-existing (some random .avi that I didn't need) format. But here are some problems:
    1. I would like for the VI to create a NEW .avi, rather than saving it into a pre-existing one.
    2. Right now, each image simply overwrites the previous one in the avi file. So the resulting avi is a 00:00 length movie with a single image (the last frame that camera viewed).
    I have what I have programmed attached. Any help would be appreciated.
    Thank you,
    B.J. Kim
    University of Michigan
    Solved!
    Go to Solution.
    Attachments:
    forum.jpg ‏1438 KB

    Here is an updated version (attached). I kept trying to incorporate the examples you showed me, and I have made a little bit of a progress.
    It now saves a new avi file, and it's not a single image movie anymore. It's got as many images as I run the VI for. BUT, it only saves the very first image the camera takes and just loops it over and over again until I press stop. So the resulting avi shows a still image of the very first view of the camera for however long I ran the VI for.
    Any suggestions on how I can fix this?
    Thank you,
    B.J.
    Attachments:
    forum2.jpg ‏1190 KB

  • Why do the file extensions (.jpg .gif .png) no longer appear when I click on a previously saved image to use that image's file name (particularly important when saving a series of images using the same root name)?

    I save a lot of images using firefox, often times from a large batch or series of images. It used to be that I would click on a previously saved image and the entire file name including the file extension (i.e. image_example.jpg) would appear in the "save as" line. Now when I click on a previously saved file, the file name appears without the file extension (i.e. image_example). Which means I have to manually type .jpg every time. For a large collection of images that I am hoping to use the same root file name and then add chronological numbers at the end, this has become incredibly frustrating, especially as it is a previously unnecessary task.
    I am using a new Macbook Pro and maybe there's something Apple related to this...? It did not happen on my old PowerBook G4. I have file extensions turned on in System Preferences.
    It should be noted that I have searched high and low and have even gone into the Apple Genius Bar where they were just confused as I was and of course ended by urging me to use Safari (shocker!) as it has all kinds of new extensions and bells and whistles. I seriously feel alone on an island with this dumb, hard to google problem. Thanks so much for any help anyone out there might have.
    I mean: is this as simple as changing a setting in about:config?
    Your assistance is greatly appreciated.

    Thanks for your response Mylenium, however like I mentioned multiple times, I did change all of my trackpad/scrolling settings in system preferences.  And if I wanted to use a normal mouse (or a tablet), I would've gotten an iMac instead of a MacBook Pro.  I travel often and work all over the place, not always with access to a decently sized workspace that would be required for using a mouse or tablet.

Maybe you are looking for

  • Adding Columns in explorer (computer)

    When you open a folder in detailed view under computer (or Word for that fact), you have the ability to add columns like date created. How do you get this column or any new columns to stick?  And how do you get the new column to display in other dire

  • Help with TRASH please

    I have some items that will not empty from Trash, even with secure trash. I tried using some simpleunix commands as sudo, but no luck. When I type this, "sudo rm -rf ~/.Trash/*" I get this: rm: /Users/tommy/.Trash/xxx/Data/2004: Directory not empty r

  • Bookmark missing after updating to Firefox 31

    Hi there! All my book marks & history setting are gone when I did my update to Firefox 31. Tried to restore from the auto bookmark backup but is prompt with "Unable to process the backup file." Tried downloading the Place Maintenance as suggested but

  • Screensaver malfunction

    For some reason my screensaver is no longer playing the photo album I selected in iPhoto. I can select an album but it just randomly chooses any photo out of the entire library. I have no idea why this started since I haven't changed it. I tried swit

  • Error message 1606 could not access network location itunes.\

    i had itunes before and it was not working so i removed all programs relate to apple and itunes and quicktime. now i m trying to install itunes again and before it even install it shows up this message says " could not access network location iTunes.