Problem in Saving Image Code

Hi, I'm been dealing with this code that should be saving an image as a JPEG format.
public static void saveAsJPEG(RenderedImage image, String file)
throws java.io.IOException {
String filename = file;
if(!filename.endsWith(".jpg"))
filename = new String(file+".jpg");
OutputStream out = new FileOutputStream(filename);
JPEGEncodeParam param = new JPEGEncodeParam();
ImageEncoder encoder = ImageCodec.createImageEncoder("JPEG", out, param);
encoder.encode(image); out.close(); }
However, when I compile the code, there's an error come out : com.sun.image.codec.jpeg.JPEGEncodeParam is abstract; cannot be instantiated
I really can't figure out the meaning of this exception. So, would somebody kindly tell me what is wrong with the code?
And another question is : What package is the ImageCodec located? Thanks a lot :)

try this out and let me know;
public static void saveAsJPEG(BufferedImage image, String file)
throws java.io.IOException {
String filename = file;
if(!filename.endsWith(".jpg")) filename = new String(file+".jpg");
OutputStream out = new FileOutputStream(filename);
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out); // Create JPEG encoder
JPEGEncodeParam jpegParams = encoder.getDefaultJPEGEncodeParam(image);
jpegParams.setQuality(1.0f, false); // Set quality to 100% for JPEG
encoder.setJPEGEncodeParam(jpegParams);
encoder.encode(image); // Encode image to JPEG and send to browser
//JPEGEncodeParam jpegPparams = new JPEGEncodeParam();
//ImageEncoder encoder = ImageCodec.createImageEncoder("JPEG", out, jpegParams);
//encoder.encode(image);
out.close(); }

Similar Messages

  • Problem in saving image to jpg

    Hello.
    I've got a problem in saving a LabView Picture in a jpg File.
    The picture id grabbed from a DirectX Livestream from a camera.
    Then I want to save it in a jpg file using the Standard LabView Functions.
    But all I get is an empty jpg File and an error:
    Check_Data_size.vi
    Error 1
    I'm using LabView 7.1.
    Has anybody got an idea how to solve the problem?

    No.  You can save a gray image to jpg, but I has to be 24 bit.
    Try save your data to bmp.  If you got the same problem, that means you fail to wire correct data format to the LabVIEW VI you're using.
    George Zou
    http://gtoolbox.yeah.net
    George Zou
    http://webspace.webring.com/people/og/gtoolbox

  • Problems hightlighting/saving images from pdf

    Hi, when I try to save a highlighted part of an image in my pdf, an error occurs: "An interal error occured." Also, when I try to save an image, it just saves them blank...
    I don't know if anyone has had the same experience(s), or perhaps even a link to someone with the same problem.
    Thanks,
    killdemall

    killdemall wrote:
    Hi, when I try to save a highlighted part of an image in my pdf, an error occurs: "An interal error occured." Also, when I try to save an image, it just saves them blank...
    More details would help. Not sure what you mean by "save a highlighted part of an image".
    What is it that you are doing, what steps are you taking to get where you are at and what tools are you using to get there?

  • Problem in Saving Images in Single Folder in Nokia...

    I want to know how to transfer images keeping it in folder. I connect my E63 with USB.I copied my "Photos" folder from my laptop,then opened "File Manager" in Nokia PC suit. There I get 2 options. 1)Memory Card 2) Phone Memory.I select memory card, In that I opened Images Folder which is default in Memory card. I paste My "Photo" folder here in "Images" folder in Memory Card.After disconnecting my phone from USB cable when in my E63 I open Media->Gallery->Images I can see all my images of that folder differently and not in a single folder "Photos" which i pasted.So what should I do?I want all images in folder as I copied and pasted. Am I suppose to create new folder manualy in Phone's Media Gallary?But in phone when I go to Office->File Manager and browse through Images folder of Memory card, I find all images in same folder "Photos" which i pasted(copied), but in Gallary->Images i find all images seperately and not in folder. What should I do? Please help me.
    Solved!
    Go to Solution.

    Hey bro thanks for reply..My main purpose for asking this question was related to xplore only. I tried xplore on my E63. When we hide folder by xplore, we browse through file manager.I mean xplore shows Folders that are in File Manager.After Hiding folder, when I go to Gallery->Images, all the images in folder which I have made hiden, are visible,but...but....all the images are converted in one images. Let me explain, Suppose my folder contains 15 images named IM1,IM2,IM3....IM15. ok. After hiding folder in gallery when i See, there are total 15 images but all are IM1.Again when I unhide folder, its normal. I also tried ticking system option along with hide option in Attributes of xplore as someone suggested me to do so.But didn't worked. My main purpose for asking to move all images into single folder was this only.I didn,t knew you too would be using xplore or else i would have directly asked you this question only.
    Thanks.
    Message Edited by ved123 on 06-Aug-2009 11:52 AM

  • Some problems creating/saving images

    What I want to do is create an image from multiple sources (a composite of 3-4 .jpg files) and save it to a file. I wanted to start off simple. I tried to create a bufferedimage, load a single .jpg file into it, and then save it. All I get is a black .jpg in the end. Any ideas?
    public class buffTest {
         public static void main(String args[]){
              Image myImage;
              BufferedImage buffImage = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB);
              Toolkit toolkit = Toolkit.getDefaultToolkit();
              myImage = toolkit.getImage("1.jpg");
              Graphics2D g = buffImage.createGraphics();
              g.drawImage(myImage, 0, 0, null);
              RenderedImage rendImage = buffImage;
              try {
                      File file = new File("newimage.jpg");
                      ImageIO.write(rendImage, "jpg", file);
              catch (IOException e) {}
    }

    Try reading the image using ImageIO.read(...) instead of toolkit.getImage(...)
    db

  • Problem in saving the image into SQL database..

    Hello,
    In my application I have to save image file (say jpg) into the database and retrieve back and display it on the applet. I am through with grabbing the pixels of the image & sending the pixel array to the servlet but I am struck in how to store the image into the database and retrieve the same.
    Can anybody please help me in this regard... its really urgent...
    Thanks in advance
    Swarna

    Hello.
    I've been researching this problem (saving images in a MySQL database) in order to accomplish a task I was assigned to. Finally I was able to do it. I'd be glad if it will be of any use.
    First of all: the original question was related to an applet. So, the post from rkippen should be read. It says almost everything, leaving the code job for us. Since I managed to write some code, I'll put it here, but I'm not dealing with the byte transferring issue.
    To obtain a byte array from a file I'd open the file with FileInputStream and use a loop to read bytes from it and save them into a ByteArrayOutputStream object. The ByteArrayOutputStream class has a method named �toByteArray()� which returns an array of bytes (byte [] b = baos.toByteArray()) that can be transferred in a socket connection, as said by rkippen.
    My problem was to save an image captured by a web camera. I had an Image object, which I converted into a byte array and saved into the database. Eventually I had to read the image and show it to the user.
    The table in the MySQL database could be:
    CREATE TABLE  test (
      id int(11) NOT NULL auto_increment,
      img blob NOT NULL,
      PRIMARY KEY  (id)
    )I had problems trying to use the �setBlob� and �getBlob� methods in the Statement object, so I used the �setBytes� and �getBytes� methods . In the end, I liked these methods most because they where more suitable to my application.
    The database operations are:
        public int insertImage(Image image) throws SQLException {
            int id = -1;
            String sql = "insert into test (img) values (?)\n";
            PreparedStatement ps = this.getStatement(sql);  // this method is trivial
            byte [] bytes = this.getBytes(imagem); // * see below
            ps.setBytes(1, bytes);
            ps.executeUpdate();
            id = ps.getGeneratedKeys().getInt(0); //Actually I couldn't make this line work yet.
            return id;
        public Image selectImage(int id) throws SQLException {
            Image img = null;
            String sql = "select img from test where id = ?\n";
            PreparedStatement ps = getStatement(sql);
            ps.setInt(1, id);
            ResultSet rs = ps.executeQuery();
            if (rs.next()) {
                byte [] bytes = rs.getBytes(1);
                img = this.getImage(bytes); // * see below
            return img;
        }* If the bytes are read directly from a file, I think it is not necessary to convert it into an Image. Just send the bytes to the database method would work. On the other hand, if the image read form the DB will be written directly into files, the bytes obtained from rs.getBytes(1) would be enough.
    The image operations are:
        public byte [] getBytes(Image image) {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            try {
                ImageIO.write(this.getBufferedImage(image), "JPEG", baos);
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            return baos.toByteArray();
        public Image getImage(byte [] bytes)  {
            Image image = null;
            ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
            try {
                image = ImageIO.read(bais);
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            return image;
        public BufferedImage getBufferedImage(Image image) {
            int width = image.getWidth(null);
            int height = image.getHeight(null);
            BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            Graphics2D g2d = bi.createGraphics();
            g2d.drawImage(image, 0, 0, null);
            return bi;
        }That's it. I hope it is useful.

  • I have problems with uploading images to my printing company have the images have been manipulated through CS6 i have saved images as jpeg but the printer company tell me they are not j peg, they will not upload images save from a camera are fine

    I have problems with uploading images to my internet printing company when  the images have been manipulated through CS6 and  i have saved images as jpeg  the printer company tell me they are not j peg,
    but images saved from my phone or camera images that have not been manipulated upload fine, What am i doing wrong?

    Save/Export them as JPG. Photoshop defaults to PSD, so make sure you select JPG and not just rename the file to .jpg.
    There are two ways to save them as JPG: Regular Save as option or Save for Web & Devices
    Take your pick.

  • Actually I have a problem is this when i submit my articles on Website the error is showin ANTI SPAM USER ID or 2nd one is this IMAGE CODE not showing Please please help me

    IMAGE CODE NOT SHOWING AND WHEN I POST ARTICLES ON WEBSITE SO THE ERROR WAS SHOWS ( ANTI SPAM USER ID ) EVEN I HAVE ALREADY LOGIN THAT WEBSITE ....
    KINDLY TELL ME ABOUT THIS PROBLEM
    == This happened ==
    Every time Firefox opened
    == Everytime when i visit websites

    Start Firefox in [[Safe Mode]] to check if one of your add-ons is causing your problem (switch to the DEFAULT theme: Tools > Add-ons > Themes).
    See [[Troubleshooting extensions and themes]] and [[Troubleshooting plugins]]
    See also [[Images or animations do not show]] and http://kb.mozillazine.org/Images_or_animations_do_not_load

  • I'm trying to export a file as .dwg for Autocad but it's not showing the dwg preview and it appears to be saving as code (lots of gobbledegook when reopening the file).  I'm on OS 10.5.8.  Never had a problem with this before.  What am I missing? Any idea

    I'm trying to export a file as .dwg for Autocad but it's not showing the dwg preview and it appears to be saving as code (lots of gobbledegook when reopening the file).  I'm on OS 10.5.8.  Never had a problem with this before.  What am I missing? Any ideas?

    First be sure login and password are OK. Sometimes the address starts wit "http://..." and sometime starts with "ftp://...". Try both normal FTP access and Scure FTP access (SFTP). At the end, contact the site's provider.

  • I am using adobe photoshop cs6. I am facing a problem. When i save any image as "save for web". After saving image it show cropped. An image show many parts of the image after saving the image. Please help me. Thanks in advance.

    I am using adobe photoshop cs6. I am facing a problem. When i save any image as "save for web". After saving image it show cropped. An image show many parts of the image after saving the image. Please help me. Thanks in advance.

    Just go back in photoshop and use the Slice Select tool, then just click and select the slice and hit delete - if you're not sure which one is the active slice just right click and find the one that has the Delete Slice option.
    It's possible you either added the slices by accident or if you received it from someone they just had the slices hidden. For the future, you can go to View > Show > Slices to display (or hide) slices.

  • Problem with burning/image saving process...

    It reported encoding error during the burning try... and it's hanged during 12 +/- hours with the saving image process (after encoding step)...
    i checked the console and saw this piece of error repeated every 2 seconds during the 12 hours:
    2006-05-11 11:24:25.279 EncoderServer[14780] CFLog (99): CFMessagePortCreateLocal(): failed to name Mach port (com.apple.idvd.EncoderServer)
    2006-05-11 11:24:27.296 EncoderServer[14781] CFLog (0): CFMessagePort: bootstrap_register(): failed 1103 (0x44f), port = 0x1403, name = 'com.apple.idvd.EncoderServer'
    See /usr/include/servers/bootstrap_defs.h for the error codes.
    Can anyone help me?
    Thanks

    it just hangs up in the audio encoding...
    It will appear to do that under normal conditions. My 1 1/2 hour iMovie project took about 30 minutes to encode the audio on this computer; two chips working hard.
    http://docs.info.apple.com/article.html?artnum=302988
    I have read that some PowerBooks can take a long time to encode a project. Like 12 hours. That doesn't seem right to me, but I've seen it here.
    Tell us more about what you're sending to iDVD. MiniDV coming from a camcorder set to record 16-bit audio, not 12-bit?

  • OutOf Memory Error while saving image of canvas

    Hi,
    I am facing a weired problem while saving the image of the graphics in Canvas. It's giving me OutOfMemory error. Here is snippet of code:
    if(cmd.equals(C.ACTION_SAVE)){
                try {
                    FileDialog fd = new FileDialog(frame, "Save ProcessInstance as JPEG", FileDialog.SAVE);
                    fd.setFile(processInstance.getProcessDefinition().getName() +processInstance.getProcessOwner() +processInstance.getProcessOwnerId() +".jpeg");
                    fd.show();
                    String name = fd.getDirectory()+fd.getFile();
                        int w = canvas.getWidth(), h = canvas.getHeight();
                        BufferedImage image = new BufferedImage(w, h,
                                BufferedImage.TYPE_INT_RGB);
                        Graphics2D g2 = image.createGraphics();
                        canvas.paint(g2);
                        g2.dispose();
                        ImageIO.write(image, "jpeg", new File(name));
                    } catch (IOException e) {
                        System.err.println(e);
                    }

    Hi,
    I tried to run garbage collector for the same and now its working fine. I want to know is there any drawback of using this approach. I am new to java and waiting for ur expert comments. I added following lines in the above code just below ImageIO.write(image, "jpeg", new File(name));:
             image = null;
                        Runtime r = Runtime.getRuntime();
                        r.gc();

  • Saved image to SDCARD, wont show up in Gallery

    hello,
    i have written a code to save image from my application folder to mobile  sdcard download folder. the code is working perfectly fine but the  problem is the image saved from my app are not visible in gallery. but  other image which are there in "download" folder are visible in gallery.
    when i restart the phone then my app saved image are visible in gallery.
    here is the code i am writing
    var fl:File = File.documentsDirectory.
    resolvePath(’Download/’ + strFileName);
    var firstHalf:ByteArray=new ByteArray();
    firstHalf=<<BInaryfile Content of my app image>>
    copyFile=new FileStream();
    copyFile.open(fl,FileMode.WRITE);
    copyFile.writeBytes(firstHalf,0,firstHalf.length);
    copyFile.close(); 

    Bad news that worked to get it into recovery mode but half way through the update it stopped and gives me the same message again "Itunes coud not connect to the ipod "mikes i pod" because it is locked with a passcode. You must enter your passcode on the Ipod before it can be used with Itunes" how do I get by that?

  • How to close saved image?

    hi 
    I can't close the saving image after i created it. It becomes read only and  i get error  unless i exit from application when i want to create it again  i think it remains open.
    Would you help me how i can solve problem?
     ofd.Filter = "Image Files|*.jpg;*.png;*.gif;*.bmp;|All Files (*.*)|*.*"
            If ofd.ShowDialog = Windows.Forms.DialogResult.OK Then
                TextBox1.Text = ofd.FileName
                Dim img As Image = Nothing
                Dim sfilename As New System.IO.FileInfo(ofd.FileName)
                Dim yol As New FileInfo(TextBox1.Text)
                Dim f As String = System.IO.Path.GetFileNameWithoutExtension(ofd.FileName)
                Dim path As String = yol.Directory.FullName & "\" & f & yol.Extension Dim fs As FileStream = sfilename.OpenRead()
    Dim outputStream As Stream = New MemoryStream()
    AddWatermark(fs, TextBox2.Text, outputStream)
    fs.Close()
    sfilename.Delete()
    img = Image.FromStream(outputStream)
    Using savingImage As New Bitmap(img.Width, img.Height, img.PixelFormat)
    Using g As Graphics = Graphics.FromImage(savingImage)
    g.DrawImage(img, New Point(0, 0))
    End Using
    savingImage.Save(path, ImageFormat.Jpeg)
    PictureBox1.BackgroundImage = Image.FromFile(path)
    End Using
    outputStream.Close()
    img.Dispose()Public Sub AddWatermark(ByVal fs As FileStream, ByVal watermarkText As String, ByVal outputStream As Stream)
            Dim img As Image = Image.FromStream(fs)
            Dim font As New Font("Verdana", 32, FontStyle.Bold, GraphicsUnit.Pixel)
            font = FontDialog1.Font
            'Adds a transparent watermark with an 100 alpha value.
            Dim color As Color = Color.FromArgb(100, 0, 0, 0)
            'The position where to draw the watermark on the image
            Dim pt As New Point(10, 30)
            Dim sbrush As New SolidBrush(color)
            Dim gr As Graphics = Nothing
            Try
                gr = Graphics.FromImage(img)
            Catch
                ' http://support.microsoft.com/Default.aspx?id=814675
                Dim img1 As Image = img
                img = New Bitmap(img.Width, img.Height)
                gr = Graphics.FromImage(img)
                gr.DrawImage(img1, New Rectangle(0, 0, img.Width, img.Height), 0, 0, img.Width, img.Height, GraphicsUnit.Pixel)
                img1.Dispose()
            End Try
            gr.DrawString(watermarkText, font, sbrush, pt)
            gr.Dispose()
            img.Save(outputStream, ImageFormat.Jpeg)
        End Sub
                                                      

    Hi,
     Here is a small example that does the same thing as your code i believe and will overwrite the opened image with the watermarked image.  Perhaps you can arrange your code to follow these steps.
    Imports System.Drawing.Imaging
    Imports System.IO
    Public Class Form1
    Private Img As Bitmap
    Private wmFont As New Font("Verdana", 32, FontStyle.Bold, GraphicsUnit.Pixel)
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    Using ofd As New OpenFileDialog
    ofd.Filter = "Image Files|*.jpg;*.png;*.gif;*.bmp;|All Files (*.*)|*.*"
    If ofd.ShowDialog = Windows.Forms.DialogResult.OK Then
    Dim frmt As ImageFormat
    If Img IsNot Nothing Then Img.Dispose()
    Using i As New Bitmap(ofd.FileName)
    frmt = i.RawFormat
    Using g As Graphics = Graphics.FromImage(i)
    Using sb As New SolidBrush(Color.FromArgb(100, 0, 0, 0))
    g.DrawString(TextBox2.Text, wmFont, sb, New Point(10, 30))
    End Using
    End Using
    Img = New Bitmap(i)
    End Using
    Img.Save(ofd.FileName, frmt)
    If PictureBox1.Image IsNot Nothing Then PictureBox1.Image.Dispose()
    PictureBox1.Image = Img
    End If
    End Using
    End Sub
    End Class
    If you say it can`t be done then i`ll try it

  • Trouble saving images on cRIO-9022

    I'm having trouble saving images on my RT target cRIO-9022 (VxWorks). I get "error 53 occurred at Write GIF File.vi LabView: Manager call not supported" when running the code. What I'm trying to do is save periodic snapshots of front panel charts/graphs locally on the cRIO and download them at a later time.
    I've also tried some of the report generation VIs and had broken arrows and compile errors. from what I've read in help and online, It seems perhaps it is not possible to do what I'm trying to do with my particular target. Is there any reason that I shouln't be able to save images locally to the RT target? has anyone else had a similar problem generating reports or saving images on the cRIO-9022?
    Thanks for any help you can provide,
    truth204

    I've run into similar problem before... I was unable, at the time, to find a good workaround for saving front panel images to file on RT because the necessary report generation functions were unsupported on the RT environment. If you are just saving data from charts and graphs, you might want to consider saving the data as a binary file or a spreadsheet/.csv style file. This is ultimately what I did in my RT application, and then I created a separate desktop application that would read the data from those exported files and reproduce the charts/graphs that were created on the RT target.
    Here is a KB describing your error, for reference: http://digital.ni.com/public.nsf/allkb/39B5B135F32902388625723B00683B27
    Cheers!
    Logan

Maybe you are looking for

  • SVG text doesn't display correctly in Illustrator

    The following SVG (generated via Cairo) displays correctly within browsers (Firefox and Safari), but not within Illustrator: the glyph symbols are drawn at the wrong scale, upside-down, and on top of one another. Is the problem within the SVG file it

  • Producer/consumer inside producer/consumer

    Hello all,  I am using a producer/consumer event structure within a producer/consumer....not sure if this is the best approach.  The main vi is setup to perform several different tests based on the user input.  It does an initialize, setup, and read

  • 1st Gen V.S. 2nd Gen

    In need of opinions... Refurb (from Apple) 1st Gen iPod Touch 8GB - $190.64 New 2nd Gen iPod Touch 8GB - $243.89 From what Ive seen, the differences are: Volume Buttons, Speaker, New Design, Genius Do you think those differences are worth $50 more??

  • Create views for Workbook

    Hello, I need to create a workbook which has the same row and key figures but each tab should have different countries. a. Should I create three different queries restricting each query to the country I need to display or b. Can I create different vi

  • Copying a CD

    In copying a CD it sometimes splits the CD into 3 sections. It then seems impossible to join the 3 sections intro the same CD Cut doesnt operate or copy Any ideas David