How to save an image as a jpeg

If i have an image now
Image finalImg = toolkit.createImage(source);
How can i save it as a jpeg?
A friend told me to use use classes from com.sun.image.codec.jpeg
because i am very new to Java, i do not quite understand this codec.jpeg, please help

That's ancient, use package javax.imageio -- I little dab'll do yah.
import java.awt.*;
import java.awt.font.*;
import java.awt.geom.*;
import java.awt.image.*;
import java.io.*;
import javax.imageio.*;
public class HelloJPEG {
    static final boolean ANTIALIASING = true;
    static final boolean FRACTION_METRICS = false;
    static final int SIZE = 96;
    public static void main(String[] args) throws IOException {
        String text = args.length > 0 ? args[0] : "Hello, World";
        Font font = new Font("Lucida Bright", Font.PLAIN, SIZE);
        FontRenderContext frc = new FontRenderContext(null, ANTIALIASING, FRACTION_METRICS);
        Rectangle2D bounds = font.getStringBounds(text, frc);
        int w = (int) Math.ceil(bounds.getWidth());
        int h = (int) Math.ceil(bounds.getHeight());
        BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = image.createGraphics();
        g.setFont(font);
        Object taHint = ANTIALIASING ?
            RenderingHints.VALUE_ANTIALIAS_ON : RenderingHints.VALUE_ANTIALIAS_OFF;
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, taHint);
        Object fmHint = FRACTION_METRICS ?
            RenderingHints.VALUE_FRACTIONALMETRICS_ON : RenderingHints.VALUE_FRACTIONALMETRICS_OFF;
        g.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, fmHint);
        g.setColor(Color.GREEN); //for St. Paddy
        g.drawString(text, -(float) bounds.getX(), - (float) bounds.getY());
        g.dispose();
        ImageIO.write(image, "jpeg", new File("hello.jpg"));
}A good source of all things Java2D is Chet Haase: http://weblogs.java.net/blog/chet/

Similar Messages

  • How to save an image as PDF?

    Hi,
    I need help o how to save an Image as PDF file?? is this possible?

    Under Getting Started in the welcome window click Create PDF
    Open your image
    File>Save As...PDF
    But I am finding that there are limitations on how big the image can be. I am trying to save a 20mb jpeg to pdf in acrobat and having issues. Good luck!

  • How to save the image in the form?

    As thread, how to save the image into a file from the pdf form - image box?
    I have Adobe Acrobat 9 Pro extended.

    Hi Sandy,
    Sorry for Delay.Could you please provide script code for the Button and in which event we want to add the code
    I want to Save the lot of images in the PDF. For that I kept Image field in the form.Here I am able to upload the images but those are not saved.
    If possible please share the details document.
    Please help me.
    Thanks,
    Ravi.

  • How to save an image as a PICT resource file?

    Can someone tell me how to save an image as a PICT resource file? I'd like to make ikons in Photoshop and save them in this format, but I 'm not finding any leads. Thanks!

    If you have Resorcerer from "ancient times" it of course can handle resource forks since that's was it's goal in life.
    There are lots of icon creation apps these days.  Do a search for "icon" on macupdate.com to see what's available.  For example that search finds:
    iconXprit
    Icon Builder X

  • How to save an image to database and retreive from it.

    how to save an image retreived from an bytearray to database and retreive back the image from database....pls specify the steps and the query.

    You can use the JDBC API for database connectivity and you can use SQL to query the database.
    JDBC tutorial: http://www.google.com/search?q=jdbc+tutorial+site:sun.com
    SQL tutorial: http://www.google.com/search?q=sql+tutorial+site:w3schools.com

  • How to save multiple images from jpeg to psd?

    I'm pretty new at this and have tons of vacation photos. Things I've read have left me terrified of leaving my images in jpeg, but I don't know how to save them all to .psd (and is that really the format I want to use?). I tried, and suddenly I'm out of space on my harddrive, so I think I've made copies of copies and have way more saved than I need. Any advice is appreciated - thanks.

    <[email protected]> wrote<br />> ...Things I've read have left me terrified of leaving my images in jpeg...<br /><br />Andrea,<br /><br />If the JPEG files are straight out of your camera, there is no harm in <br />"leaving" them as-is...  they don't degrade from just sitting there.<br /><br />The possible degradation of JPEG files comes from saving as a JPEG - <br />typically after you have done an edit to the image.<br /><br />One good way to approach the issue:  when you open an image for editing, <br />before you do anything, click the menu File > Save As...  and then choose <br />the PSD file type.  This will make a copy for you to work with, which will <br />NOT degrade as you save, re-edit, re-save, etc.  After you're finished <br />working it over, if you need a JPEG copy, use the File > Save As...  and <br />select JPEG to make an edited copy in the smaller file format.  (File > Save <br />For Web is also useful for this - it allows you to set your quality and size <br />parameters on-the-fly as you save)<br /><br />HTH,<br /><br />Byron

  • Do you know how to save a VB Form as JPEG image?

    I have a form displaying graph and knob (dial meter) output that is output only. I want to save the form "image" as a JPEG file (or other picture format) so I can display it in a web page for info purposes only. I plan to "refresh/rewrite" the JPEG every minute of so. I have seen software that does this. It is nice for presenting info in the browser (to non wintel machines for example).
    Any idea how to do it?
    Thanks

    Also, if you're using VB.NET, this is pretty easy ... something like this would work:
    Private Shared Function BitBlt( _
    ByVal hdcDest As IntPtr, _
    ByVal nXDest As Integer, _
    ByVal nYDest As Integer, _
    ByVal nWidth As Integer, _
    ByVal nHeight As Integer, _
    ByVal hdcSrc As IntPtr, _
    ByVal nXSrc As Integer, _
    ByVal nYSrc As Integer, _
    ByVal dwRop As Integer _
    ) As Boolean
    End Function
    Private Shared SRCCOPY As Integer = &HCC0020
    Private Sub SaveFormToFile(ByVal sourceForm As Form, ByVal filename As String)
    Dim formGraphics As Graphics = sourceForm.CreateGraphics()
    Dim
    bufferRect = sourceForm.ClientRectangle
    Dim buffer As Image = New Bitmap(bufferRect.Width, bufferRect.Height, formGraphics)
    Dim bufferGraphics As Graphics = Graphics.FromImage(buffer)
    Dim formDC As IntPtr = formGraphics.GetHdc()
    Dim bufferDC As IntPtr = bufferGraphics.GetHdc()
    BitBlt(bufferDC, 0, 0, bufferRect.Width, bufferRect.Height, formDC, 0, 0, SRCCOPY)
    bufferGraphics.ReleaseHdc(bufferDC)
    formGraphics.ReleaseHdc(formDC)
    bufferGraphics.Dispose()
    formGraphics.Dispose()
    buffer.Save(filename, System.Drawing.Imaging.ImageFormat.Jpeg)
    buffer.Dispose()
    End Sub
    If you copied and pasted this to your form, you could then save the form to a .jpg file anytime you want by passing the Me reference in for this first parameter and the filename that you want to save it to. For example, if you wanted to create a .jpg file in the root directory of your C drive called "Test.jpg":
    SaveFormToFile(Me, "Test.jpg")
    - Elton

  • How to save greyscale image as jpeg?

    Anyone know how to save a greyscale image as a jpeg in labview?

    Hi Jonathan,
    If I understand you correctly, you had a greyscaled image, which you applied color to and now want to save this new image.  Before I jump into possibly solutions, I have a question for you. 
    Are you using any IMAQ, Motion, or Vision VIs?  If not, try using the Picture Control VIs - specifically, the "Write JPEG File.VI"
    If that won't work, please post a small piece of code illustrating the issue.
    Thanks!
    Janell Rodriguez | Applications Engineer | National Instruments

  • How to save an image from canvas to jpeg2000 format?

    good day! i would like some help about jj2000. i wish to save an image from canvas to a jpeg2000 format file. how will i do it using the jj2000? i just need to save it to a file.
    please help!!!
    thank you in advance!
    lrds

    I am not familiar with Jpeg2000, but the easiest way I've found to go from Java to a JPeg file is with Java Adavanced Imaging (JAI) package from Sun. Take a look at it and see if it meets your requirements.

  • How to save Buffered Image with variable transparency in a file.

    Hi,
    I need to save BufferedImage (type ARGB) in a file.
    Transparency in this image is a function of position. Who knows, what would be the best suggestion for type of file to store this image (probably not JPEG) and which package would be appropriate. A sample of code would be higly desirable. Please help, thank you in advance.

    Your can use the ImageIO-API if your software runs under JVM1.4 or you must use the JAI (Advanced Imaging API) ...

  • How to save an image to file without rendering to screen?

    Does anyone know of a way I can save a buffered image to a file (as a jpg) without having to render it to a screen first? I can create the file fine if I place the image on a JPanel first. However when I try to save the image directly to a file, the program hangs when I try to render the image to a Graphics object. Is there some sort of initialisation carried out on the image when it is displayed on screen which I need to carry out to save the image offscreen?
    Just as a background, what I am trying to achieve is to create a chart (using Monarch Charts library) based on a supplied set of data, and then to save this chart as a jpg. It works fine if I first display the chart in a JPanel but not when I try to save it offscreen.
    Can anyone help me out here?
    Thanks,
    Ciaran

    Here's the code I use in JFreeChart to create a buffered image - the third line draws the chart using the Graphics2D obtained from the BufferedImage:
        public BufferedImage createBufferedImage(int width, int height) {
            BufferedImage image = new BufferedImage(width , height, BufferedImage.TYPE_INT_RGB);
            Graphics2D g2 = image.createGraphics();
            this.draw(g2, new Rectangle2D.Double(0, 0, width, height), null);
            g2.dispose();
            return image;
        }Writing to a JPEG can be done like this (method taken from the ChartUtilities class in JFreeChart):
        public static void writeChartAsJPEG(OutputStream out, JFreeChart chart, int width, int height)
            throws IOException {
            BufferedImage image = chart.createBufferedImage(width, height);
            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
            JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(image);
            param.setQuality(1.0f, true);
            encoder.encode(image, param);
        }If you want to try some running code, download JFreeChart from:
    http://www.object-refinery.com/jfreechart/index.html
    ...then run this application:
    package com.jrefinery.chart.demo;
    import java.io.File;
    import com.jrefinery.chart.JFreeChart;
    import com.jrefinery.chart.ChartFactory;
    import com.jrefinery.chart.ChartUtilities;
    import com.jrefinery.chart.demo.DemoDatasetFactory;
    import com.jrefinery.data.XYDataset;
    public class ChartToFile {
        public static void main(String[] args) {
            XYDataset data = DemoDatasetFactory.createTimeSeriesCollection2();
            JFreeChart chart = ChartFactory.createTimeSeriesChart("Sample Chart", "Time", "Rate", data, true);
            File file = new File("MyChart.jpg");
            try {
                ChartUtilities.saveChartAsJPEG(file, chart, 400, 300);
            catch (java.io.IOException e) {
                System.out.println(e.getMessage());
    }Regards,
    Dave Gilbert
    www.object-refinery.com

  • How to save iPhoto images on disc

    Trying to save space on My HD, can't figure out how to save an album to a disc

    after having used iPhoto 08 for a long time the link between the program and the source files broke. i have a hard time restoring the library. how can i import ALL images on my harddisc into iphoto? is there a function that scans and finds all images automatically?
    You really would not want to do this - you would have a mess - many duplicates and lots of images that have nothing to do with photos
    Tell us more about your problem - what is happening and how it occurred
    Most likely you have all of your original Photos in the originals folder of your iPhoto library and simply quitting iPhoto, dragging the iPhoto library to the desktop, launching iPhoto and creating a new library and dragging each folder from the originals folder in your iPhoto library on the desktop onto the iPhoto icon in the dock (check to be sure that the iPhoto preference to split items imported from the finder is NOT checked) - this will recreate your events
    If this is not an option their probably is still help
    LN

  • How to save layer image

    Hi, I'm a newbe
    I need to save the image of a layer, but my asset is a psd file, how do I get the image from it?
    Thx

    hi nnzz! welcome to the forum!
    a layer's image pixels are gotten in the same way regardless of the source.
    if your effect is applied to it, you'll have the pixels handed to you from AE automatically.
    in any case you can get the layer's source item and render it through the render suite.
    once you have the pixel datayou can process it and save it in any way you like.

  • How to save content of JPanel into jpeg or png file

    I have to independent classes: Class A and Class B. Each class constructs its own graphical objects:
    Class A {
    //do something
    public void paintComponent(Graphics g)
    int x = 0;
    int y = 0;
    int w = getSize().width;
    int h = getSize().height;
    bi = new BufferedImage(
    w,h,100,BufferedImage.TYPE_INT_RGB);
    g2d = bi.createGraphics();
    // draw lines
    g2d.drawImage(bi,0,0,ww,hh, this);
    Class B {
    int x = 0;
    int y = 0;
    int w = getSize().width;
    int h = getSize().height;
    bi = new BufferedImage(
    w,h,100,BufferedImage.TYPE_INT_RGB);
    g2d = bi.createGraphics();
    // draw lines
    g2d.drawImage(bi,0,0,ww,hh, this);
    Two buffered images get properly displayed within JPanel component. However, I need to save two those results into one file. If I add saving file routine into every class, at best I can only get them to be in two different files.
    Please let me know if anyone can help me with this problem.
    Thanks,
    Jack

    You didn't mention what should be the format of file that the combines the images. Here are two options:
    1. Create another BufferedImage, and draw the BufferedImages from class A and B over this BufferedImage and save it as JPEG or PNG.
    In each of the class, you can add a method like getBufferedImage(), which would return the local BufferedImage. A third class, say class C, needs to call this method in each of the classes, and then draw the BufferedImages returned by these methods over another BufferedImage. Save this BufferedImage as a JPEG or PNG.
    A disadvantage of this approach is that you can't easily retrieve the individual images from the resulting file.
    2. Create a single zip file by adding the individual JPEG/ PNG images created from the BufferedImage in class A and B.
    Here is an example that creates single zip file of JPEG images from an array of BufferedImageObjects:
    public static void zip(String outfile, BufferedImage bufimage[]){
         if(bufimage == null) return;
         try{
             File of = outfile.endsWith(".zip")? new File(outfile): new File(outfile+".zip");
             FileOutputStream fos = new FileOutputStream(of);
             ZipOutputStream zos = new ZipOutputStream(fos);
             for(int i=0;i<bufimage.length;i++){
                 try{
                    ByteArrayOutputStream boutstream = new ByteArrayOutputStream();
                    JPEGImageEncoder enc = JPEGCodec.createJPEGEncoder(boutstream);
                    enc.encode(bufimage);
    ZipEntry entry = new ZipEntry("bufimage"+(new Integer(i)).toString()+".jpg");
    entry.setMethod(ZipEntry.DEFLATED);
    zos.putNextEntry(entry);
    byte[] fileBuf = boutstream.toByteArray();
    zos.write(fileBuf,0,fileBuf.length);
    zos.closeEntry();
    } catch (Exception e){ e.printStackTrace();}
    zos.flush();
    zos.close();
    }catch(Exception e) {e.printStackTrace();}
    The above method uses the JPEG codec and the zip package, both of which available in J2SE. In other words, you need to import com.sun.image.codec.jpeg and java.util.zip packages.
    With this approach, you can easily retrieve the individual JPEGs using the java.util.zip package.

  • PSE 7 Windows 7, 1.5 TB disk, how to save the image

    I got a new PC with a 1.5 TB hard disk, running Windows 7 and PSE 7. With the help of this Forum I managed (changing the scratch disk with  ALT and CONTROL) to start and work with PSE 7.
    However, now I am unable to save the image, again the error message is: Scatch disk full.
    Any ideas how to solve the problem? 

    If you have a spare volume, allocate that as the scratch disk first, followed by the C drive as the second scratch disk.
    Sometimes you run short of RAM if you have lots of open images. Try saving and closing as you work.

Maybe you are looking for