Resizing JPEG images

Hey guys,
I have the following code:
public static void resize(String original, String resized, int size,
                              int dimension, float factor)
            throws Exception
        if ((dimension != HEIGHT) && (dimension != WIDTH))
            dimension = WIDTH;
        try
            // get original image
            Image originalImage = new ImageIcon(original).getImage();
            Image resizedImage = null;
            int imageWidth = originalImage.getWidth(null);
            int imageHeight = originalImage.getHeight(null);
            if (dimension == WIDTH)
                resizedImage = originalImage.getScaledInstance(
                        size, (size * imageHeight) / imageWidth,
                        Image.SCALE_SMOOTH);
            else
                resizedImage = originalImage.getScaledInstance(
                        (size * imageWidth) / imageHeight, size,
                        Image.SCALE_SMOOTH);
            // this code ensures that all the pixels in the image are loaded
            Image temp = new ImageIcon(resizedImage).getImage();
            // create the buffered image
            BufferedImage bufferedImage = new
BufferedImage(temp.getWidth(null),
                    temp.getHeight(null), BufferedImage.TYPE_INT_RGB);
            // copy image to buffered image
            Graphics g = bufferedImage.createGraphics();
            // clear background and paint the image
            g.setColor(Color.white);
            g.fillRect(0, 0, temp.getWidth(null), temp.getHeight(null));
            g.drawImage(temp, 0, 0, null);
            g.dispose();
            // sharpen/soften (depending on factor (-ve for sharpening, +ve
for softening)
            float[] array = {0, factor, 0, factor, 1 - (factor * 4),
                factor, 0, factor, 0};
            Kernel kernel = new Kernel(3, 3, array);
            ConvolveOp cOp = new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP,
null);
            bufferedImage = cOp.filter(bufferedImage, null);
            // write the jpeg to a file
            OutputStream out = new FileOutputStream(resized);
            // encodes image as a JPEG data stream
            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
            com.sun.image.codec.jpeg.JPEGEncodeParam param =
encoder.getDefaultJPEGEncodeParam(bufferedImage);
            param.setQuality(0.7f, true);
            encoder.setJPEGEncodeParam(param);
            encoder.encode(bufferedImage);
        catch (Exception e)
            throw e;
    }which I use for making thumbnails and resizing images uploaded to my site. Thumbnails work fine (possibly due to the smaller size) but when I resize an image I get lots of horizontal lines across resized image.
The funny think is that when I use this method just in a simple application, running directly under JDK 1.4.1_02 then everything works fine and images turn out fine.
When the above code runs as a part of my web application, thumbnails work, but larger images end up with the lines across them.
Any ideas??
I thought it might have had something to do with the factor parameter I use so I tested it just using 0.0 and the same problem occurs.
I run Apache 2.0.44 with Tomcat 4.1.18, which by the way also runs with JDK 1.4.1_02 so JDK is not the problem.
Any help is greatly appreciated.
Cheers,
Tom

hey tom,
i also use this code and also had these problems. i solved it by adding just one line after your if-else: originalImage.flush();
else {
resizedImage = originalImage.getScaledInstance (size * imageWidth)/imageHeight, size, Image.SCALE_SMOOTH);
originalImage.flush();
// this code ensures that all the pixels in the image are loaded
Image temp = new ImageIcon(resizedImage).getImage();
.

Similar Messages

  • Marydee-You asked me about resizing apps for jpeg images & how 2 get info

    Marydee- You asked me about resizing apps for jpeg images. And you also asked how to get photo info for each image in iphoto
    Here's what I found in the iPhoto6 Help Menu:
    Showing a photo's image and camera information
    iPhoto stores EXIF information with each photo in your library. This information includes the photo's image size, the date and time it was taken, and the type of camera it was taken on, as well as important exposure information, such as the shutter speed, aperture, and film ISO.
    To show image and camera information:
    Select the photo and choose Photos > Get Info.
    You can also see a photo's title, date taken, rating, format, and comments by clicking the Information button in the bottom-left corner of the iPhoto window.
    Also please take a look at these prior discussions in iPhoto Forum/s:
    http://discussions.apple.com/thread.jspa?messageID=3212997&#3212997
    http://discussions.apple.com/thread.jspa?messageID=4535542&#4535542
    http://kstudio.net/re.html
    Hope the above helps and good luck on this.
    (3) G4 PM's/(3) S-Drives/Sony TRV900/Nikons/6FWHD's/PS7/iLife06/FCPHD/DVDSP/etc.   Mac OS X (10.4.8)  

    Marydee- You asked me about resizing apps for jpeg images. And you also asked how to get photo info for each image in iphoto
    Here's what I found in the iPhoto6 Help Menu:
    Showing a photo's image and camera information
    iPhoto stores EXIF information with each photo in your library. This information includes the photo's image size, the date and time it was taken, and the type of camera it was taken on, as well as important exposure information, such as the shutter speed, aperture, and film ISO.
    To show image and camera information:
    Select the photo and choose Photos > Get Info.
    You can also see a photo's title, date taken, rating, format, and comments by clicking the Information button in the bottom-left corner of the iPhoto window.
    Also please take a look at these prior discussions in iPhoto Forum/s:
    http://discussions.apple.com/thread.jspa?messageID=3212997&#3212997
    http://discussions.apple.com/thread.jspa?messageID=4535542&#4535542
    http://kstudio.net/re.html
    Hope the above helps and good luck on this.
    (3) G4 PM's/(3) S-Drives/Sony TRV900/Nikons/6FWHD's/PS7/iLife06/FCPHD/DVDSP/etc.   Mac OS X (10.4.8)  

  • How to get crisp jpeg images for slideshow on a Mac with Final Cut?

    Hi, I imported a large number of jpegs into Final Cut Pro and when I export to Quicktime Movie (not modifying the sequence size or settings I notice the quality of the jpeg images looks rather washed out and a bit fuzzy. The image dimensions of the jpegs are actually 2848 x 4272 and I was originally using a sequence setting of 720 by 480 (which scaled the images to about 12%). I experimented with doubling the sequence setting to 1440 by 960 and scaled the images to about 25.5% - still a bit washed out look.
    Basically this will be a presentation on a computer and output via projection. Looking for best possible and clearest photos. I experimented with iPhoto and when you play a slideshow it looks very crisp - this is what I am aiming for. When I export using the Slideshow export at the largest size 640 by 480 in iPhoto to quicktime - the quality seriously deteriorates.
    What would be the best way to maintain the crispness of the photos in Final Cut for an export to Quicktime that would be show on a Mac via a projector? Thank you

    Hi Nick, I do see information on creating a slideshow with Quicktime at: http://www.apple.com/quicktime/tutorials/slideshow.html
    however it appears Quicktime X removed that capability. There is no 'open image sequence' option from the File menu in Quicktime X.
    If I do end up sticking with Final Cut - would you recommend any codec and/or dimension size that would result in the best quality or the most crisp image? I also need a few fade in's and out's on various parts - I don't believe I would have the control without Final Cut.
    Would resizing the image files in Photoshop to 1920 pixels by 1280 before importing them into Final Cut result in crisper images? Thanks.

  • How do I change the JPEG image size in PSE-12 when opening from RAW

    Switching from PSE-9 to PSE-12. When a JPEG image is opened RAW in PSE-12 the size is 18.72" Wide x 12.48" high 300 DPI. The same image in PSE-9 is 23.4" wide x 15.6" High 240 DPI. How do I get PSE-12 to open the image as in PSE-9?

    Uncheck the boxes at the bottom of the dialog Scale styles and resample Image so that only constrain proportions is checked. If you the change the resolution box from 240 to 300 you will get back to your original dimensions.
    This is a meaningless thing to do, you still have the exact same number of pixels, you have only changed the metadata number in the file for ppi, and your prints are not affected by this number.
    You could also use the same method to change the dimensions to 6 x 4 or 9 x 6 etc.
    There are some cases (actually most cases) where you need to CROP the photo to change the dimensions, when the aspect ratio of the original photos is different than the aspect ratio of the final photo; the specific case in 99jon's example is the only case you ever want to change dimensions using Image->Resize->Image Size, where the aspect ratio doesn't change from 6x4 to 9x6 (or 12x8 or 18x12 or ...), and even then, you could do the same thing simply by telling the printer the size you want, you don't really need to do anything in PSE.

  • How do you resize a image/picture and save it?

    Hello, I know how to resize a image. But how do I save a new image/pictures has Jpeg with new size properties?

    Use File>Save As or File>Save for web. Either of these will create a new document as long as the name is different or is in another folder.

  • Better to resize JPEGs for a QT sequence before or while exporting from QT?

    I have several thousand JPEG files shot as a time-lapse sequence, at my DSLR camera's smallest size of 4288 by 2848 pixels. I want to sequence them as a QuickTime movie, for a final frame size of 1920 by 1080 pixels. Is it okay to batch resize the JPEGs in a photo application (PhotoMechanic or Photoshop) before creating the Quick Time Pro sequence and then exporting it as a .MOV, or am I better off sequencing the JPEGs in QuickTime Pro, then exporting them as a 1920 by 1080 pixel movie file?
    The last time I did this I let QTPro do the resizing while exporting, and it took over an hour to generate the .MOV file. Is that to be expected given the "fast" computer I'm using?

    Resize the image files prior to import to QuickTime.
    It'll be faster on your machine.

  • Help in resizing an image

    I am an artist thatI needs to resize images in order to send them for review for art shows and reviews.  An example is one file that is currently 3600 x 2736 px with a resolution of 180  - the size needs to be reduced to 600 x 800 px but the resolution needs to be increased to 300.
    Is there a correct way to go about this, can I accomplish both at the same time
    Do I check the boxes for    _ Scale Styles
                                            _Resample Image
                                            _Constrain Proportions
    I want to make sure that I am not harming the image.
    Also, when I download my photos with the digital camera card, they are always loaded as 180 dpi.  Is that a default setting on Elements or is is the camera setting?
    Thanks for any advise, like many artists, I am not very savvy with the computer or software stuff.
    Help is much appreciated!

    What I had to do to resize my images that I wanted to send off for printing was to click on the following:
    Full Phot Edit
    Image
    Resize
    Image Size
    Change Resolution to 300 ppi
    Save as baseline standard
    Then export the Jpeg.
    The company wanted my photos at least 300 ppi for best quality.  I don't think she cared about the pixel size, but I guess you could change that as well.  Hope this helps a little.  Took me days to figure out how to send off for printing.

  • How to import a jpeg image into premier elements 12?

    how do  i import a jpeg image into premier elements 12?

    chuckx
    Just for background information, what computer operating system is your Premiere Elements 12 running on?
    The generalized answer is Add Media/Files and Folders/Projects Assets from where you drag the photo to the Expert view Timeline.
    But all that can generate a mountain of questions about the photo and the project into which it will be going
    a. what are the pixel dimensions of the photo - will or will I not have to resize or crop/resize the photo for the project
    b. is the photo going into a project that will consist of photos and videos
    c. if video inclusion, that leads to questions about the properties of the video so that you can set the project preset to match those
    d. that leads to questions on the best size to have your photo before you import them into this project.
    So, one simple question generates a lot of side questions.
    Please let us know how we might help to sort out the details for your Premiere Elements workflow and its source media.
    Thank you.
    ATr

  • Problem importing some jpeg images

    **** all
    For some reason I cant import selected jpeg images, about 75% of them are grayed out for some reason, the images are jpegs I have collected on line and are the only images I seem to have a problem with.
    Any idea way ?
    Thanks

    yes I have the actual image, I found the problem .
    they where all grayed out cause of the image size, I downloaded desktop images.
    I'm glad I worked it out cause I'm using these images as backgrounds and, have 487 of them. I ran them through easybatchphoto and resized the width on all of them to 800. now they all work fine.

  • Bridge Exports Changes Resolution from 300 to 72 dpi, resizing my image

    I like to use Bridge (CS5) to export my photographs for printing, and frequently I will use the Export feature to resize the images (e.g., 5x7 vs full size), but every time I export it recharacterizes the images as 72 dpi, vs the 300 dpi I prefer. 
    Consistent with some of the previous postings (~2 yrs ago) I have seen on this topic the exported images are now "sized" much bigger (29"x20" for what should have been ~5"x7"), and hence expectantly I haven't lost any resolution, but it's aggrevating to have the dpi changed.
    Can anyone tell me how to export without having the dpi changed?
    And while I'm at it, can anyone confirm that I'm not loosing image resolution?
    Thanks so much!!

    Can anyone tell me how to export without having the dpi changed?
    Can't find any other settings to change and just having tested it I can confirm that it sets ppi (it is pixels per inch -ppi- for a digital file which is made from pixels and dots per inch -dpi- from the ink dots of a print ) to 72.
    And while I'm at it, can anyone confirm that I'm not loosing image resolution?
    You already stated yourself that you did not loose pixels, therefor the size of the files stays the same. It is just a mater of figures. 300 ppi means a larger concentration per inch and 72 pixels per inch means a smaller concentration of pixels per inch. Given the same amount of pixels for both settings this means a smaller image dimension for 300 ppi and a larger image dimension for the 72 ppi.
    300 ppi is some 'magic' number from printed press, but it really depends on the need of the job related printing machine. If you have a small image and need to look closely it should have a larger concentration per inch to reflect its sharpness.
    However theoretically you would almost have the same visible quality when printed on 72 at billboard sizes. That's because you always have a large distance between your eyes and the bill board. If you look closely you will see the dots (because the billboard is a product of ink dots…) but of course it is not meant to study at that close range.
    The same is for judging sharpness on your computer. Ideally you do so at 100 % for correct judgement at real size pixels. But in reality there will be almost no situation you will study a print at that same distance
    Any thoughts on why these would be different?   And am I fretting over things unncessarily?
    Only guesses, the use a different algorithm or calculation scheme, in my case I tried a Canon Raw (converted to DNG) without any ACR settings then the basics applied and found that Bridge export jpeg 11 creates larger files then using PS.
    But there are some other concerns I have and that certainly would make me fretting in use of export module:
    First of all I almost never use it, merely in this cases for testing, because using the menu tools give a shortcut to Photoshop / Batch and inhere I have created several dedicated resizing and resaving actions that also places the files in preset folders.
    But with this small test I found out that
    a: it changes ppi to 72 ppi, not a very big deal but I did not asked for it nor did I wanted it.
    b: it converts my Adobe RGB color space to sRGB and I certainly did not want that without my explicit wish for this conversion, so this is more then a bit worrying to my concern.
    c: it seems to apply a sharpness that I certainly did not want to happen without my knowledge, and this rules the use of the export module out completely.
    Since I only tried a DNG file without settings or retouch/developing  in Photoshop the jpeg generated by PS was not very sharp. This makes sense to me because I have set my basic ACR to apply sharpening only to preview. There are a lot of different sharpening theories around but I use one in PS itself. So I was a bit shocked to learn that the export module did all those for me unwanted and not adjustable settings putting me completely out of control…
    So if you want to have full control about things happening under the hood yourself just start creating actions in PS, it is very easy to record an action and even more easier to play it. Instead of every time dragging files to export module and always recheck the image options (it seems to reset itself always to jpeg quality 8 on my system) only select the files you want to resize and choose menu tool / Photoshop Batch and select the wanted action. hit OK and your almost done, PS does the rest.
    The great thing of the latest PS CS6 action pallet is the extension with a so called 'insert conditional' that let's you create an 'if - then else' action for both landscape and portrait resizing actions so you don't need the 'constrain to fit' or 'fit image' option. Just once create an action for both resizing dimensions and then create a new action with insert conditional. choose If image is landscape play action…. / else play action….
    It is really a very productive way. I have a lot of actions (organized in sets for better overview) and even one that creates 4 different sizes in 4 different folders using 1 go in Bridge

  • How to resize GIF images

    Hi
    I used acme.jar to wirte gif images to a local disk . i worked fine , but iam facing problem in resizing these images , when i resize these images i get black background color in tat images .. can any body help me regarding this.....
    thumbImage = scaleToSize(imageWidth, imageHeight, thumbImage);
    Graphics2D graphics2D = thumbImage.createGraphics();
    graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
         RenderingHints.VALUE_INTERPOLATION_BILINEAR);
         graphics2D.drawImage(image,0,0,     thumbWidth,thumbHeight,null);
    out = new BufferedOutputStream(new FileOutputStream(newFilePath));
    GifEncoder gife = new GifEncoder(image,out);     
    gife.encode();
    this is my code .....

    Following is my code:
    public final String dealFile(ActionMapping mapping,ActionForm form,
                   HttpServletRequest request) throws FileNotFoundException, IOException{
              GroupForm gForm = (GroupForm) form;
              ActionMessages errors = new ActionMessages();
              // retrieve the file representation
              FormFile file = gForm.getPictFile();
              if (file == null) {
                   errors.add("FileNeeded", new ActionMessage("error.photo.filenull"));
                   saveErrors(request, errors);
                   return "failure";
              // has the maximum length been exceeded?
              Boolean maxLengthExceeded = (Boolean) request
                        .getAttribute(MultipartRequestHandler.ATTRIBUTE_MAX_LENGTH_EXCEEDED);
              if ((maxLengthExceeded != null) && (maxLengthExceeded.booleanValue())) {
                   errors.add("maxLengthExceeded", new ActionMessage(
                             "error.photo.length"));
                   saveErrors(request, errors);
                   return "failure";
              // retrieve the file name
              String fileName = file.getFileName();
              // judge file type
              String fileType = fileName.substring(fileName.lastIndexOf(".") + 1);
              if (!(fileType.equalsIgnoreCase("jpg")
                        || fileType.equalsIgnoreCase("jpeg")
                        || fileType.equalsIgnoreCase("gif") || fileType
                        .equalsIgnoreCase("png"))) {
                   errors.add("NotPict", new ActionMessage("error.photo.wrongformat"));
                   saveErrors(request, errors);
                   return "failure";
              Date date = new Date();
              Random r = new Random(date.getTime());
              // ������������
              String newFileName = request.getSession().getId() + r.nextInt(10000)
                        + "." + fileType;
              String filePath = null;
              String newFilePath = null;
              // the directory to upload to
              String uploadDir = servlet.getServletContext()
                        .getRealPath("/resources")
                        + "/groupphoto/" + DateUtil.asShortString(date)+"/";
              // prepare directory if not exists
              File dirPath = new File(uploadDir);
              if (!dirPath.exists()) {
                   dirPath.mkdirs();
              // retrieve the file data
              InputStream stream = file.getInputStream();
              // write the file to the file specified
              OutputStream bos = new FileOutputStream(uploadDir + newFileName);
              int bytesRead = 0;
              byte[] buffer = new byte[8192];
              while ((bytesRead = stream.read(buffer, 0, 8192)) != -1) {
                   bos.write(buffer, 0, bytesRead);
              bos.close();
              buffer = null;
              filePath = dirPath.getAbsolutePath() + Constants.FILE_SEP
                        + newFileName;
              File _file = new File(uploadDir + newFileName);
              Image src = ImageIO.read(_file); // ����Image����
              int width = src.getWidth(null); // ����������
              int height = src.getHeight(null);// ����������
              // convert the picture to picture within 100x100 and save to a file with
              // prefix
              // 100x100_ for later listing purpose.
              newFilePath = dirPath.getAbsolutePath() +Constants.FILE_SEP
                        + "100x100_" + newFileName;
              int newWidth = 0;
              int newHeight = 0;
              int bigger = width <= height ? height : width;
              if (bigger > 100) {
                   if (width >= height) {
                        newWidth = 100;
                        newHeight = height * 100 / width;
                   } else {
                        newHeight = 100;
                        newWidth = width * 100 / height;
                   ImageUtil.convert(filePath, newFilePath, newWidth, newHeight);
              // close the stream
              stream.close();
              _file = null;
              src = null;
              dirPath = null;
              String url = request.getContextPath() + "/resources" + "/groupphoto/"
              + DateUtil.asShortString(date)+"/"+ "100x100_" + newFileName;
              return url;          
         }

  • Why when I resize an image does it looks less sharp and poor quality?

    I've been using Photoshop since CS3 and have never had thus problem before. I used to create websites using WordPress for clients and have created many different logo images without any issues. Now however I'm doing it for muself and I'm having problems when I resize the images for web use.
    Here are a few examples. The first is a 1400x1400 image that I'm going to use for a podcast. iTunes requires this size and it looks good to my eye. When you look at the resized image however you'll see that it is not quite as sharp.
    1400x1400 http://d.pr/i/SrtJ
    300x300 http://d.pr/i/IqtI
    Logo at http://safetydad.net
    Twitter page http://twitter.com/thesafetydad
    I've tried all different things to get it to look good at any size but no mater what when the image gets resized (especially by a CMS or Twitter) it looks like crap. I've tried saving as png, jpeg, flatteing before resizing, resizing the psd, saving as jpeg then resizing, using save for web option but no matter what it doesn't look right.
    What am I doing wrong?

    When you scale down, you will lose some of the sharpness because it is removing pixels from the image, and Photoshop is trying to figure out how to remove pixels, and reassemble the edges of the image.. As a result, when some of that shading is removed, it begins to blur. Make sure when scaling down an image (image - image size) that you set the resampling to bicubic sharper. This will help to reduce the blur from the pixel removal.
    Also, you can go to filter - sharpen - unsharp mask - and work on bringing back some of the sharpness there as well.
    For your twitter logo - I would make a separate logo for it, because the text is difficult to read over it. Sorry - just my opinion there.
    You may have tried these things already - but if not - hopefully it helps
    On the other note - I think you might be hyper-critical of the changes...

  • Failed to resize jpeg file

    Hello! I have a method that do resize of the jpeg image:
    private Boolean resizePhoto(String fileName, int destWidth, int destHeight, String destFile) {
            FileInputStream fileInputStream = null;
            FileOutputStream fileOutputStream = null;
            float scaleX,scaleY;
            try {
                fileInputStream = new FileInputStream(fileName);
                SeekableStream s = SeekableStream.wrapInputStream(fileInputStream, true);
                RenderedOp image = JAI.create("stream", s);
                ((OpImage) image.getRendering()).setTileCache(null);
                scaleX = (float)destWidth / (float)image.getWidth();
                if(destHeight==0) scaleY = scaleX;
                else scaleY = destHeight / image.getHeight();
                ParameterBlock pb = new ParameterBlock();
                pb.addSource(image);                    // The source image
                pb.add(scaleX);                         // The xScale
                pb.add(scaleY);                         // The yScale
                pb.add(0.0F);                           // The x translation
                pb.add(0.0F);                           // The y translation
                pb.add(new InterpolationNearest());     // The interpolation
                RenderedOp resizedImage = JAI.create("scale", pb, null);
                fileOutputStream = new FileOutputStream(destFile);
                JAI.create("encode", resizedImage, fileOutputStream, "JPEG", null);
                return true;
            } catch (FileNotFoundException ex) {
                System.out.println("FileNotFoundException");
                ex.printStackTrace();
                return false;
            } finally {
                try {
                    fileInputStream.close();
                    fileOutputStream.close();
                } catch (IOException ex) {
                    System.out.println("IOException");
                    ex.printStackTrace();
                    return false;
        }But cannot resize certain photos and getting an error:
    Error: One factory fails for the operation "jpeg"
    Occurs in: javax.media.jai.ThreadSafeOperationRegistry
    java.lang.reflect.InvocationTargetException
            at sun.reflect.GeneratedMethodAccessor4.invoke(Unknown Source)
            at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
            at java.lang.reflect.Method.invoke(Method.java:597)
            at javax.media.jai.FactoryCache.invoke(FactoryCache.java:130)
            at javax.media.jai.OperationRegistry.invokeFactory(OperationRegistry.java:1682)
            at javax.media.jai.ThreadSafeOperationRegistry.invokeFactory(ThreadSafeOperationRegistry.java:481)
            at javax.media.jai.registry.RIFRegistry.create(RIFRegistry.java:340)
            at com.sun.media.jai.opimage.StreamRIF.create(StreamRIF.java:110)
            at sun.reflect.GeneratedMethodAccessor4.invoke(Unknown Source)
            at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
            at java.lang.reflect.Method.invoke(Method.java:597)
            at javax.media.jai.FactoryCache.invoke(FactoryCache.java:130)
            at javax.media.jai.OperationRegistry.invokeFactory(OperationRegistry.java:1682)
            at javax.media.jai.ThreadSafeOperationRegistry.invokeFactory(ThreadSafeOperationRegistry.java:481)
            at javax.media.jai.registry.RIFRegistry.create(RIFRegistry.java:340)
            at javax.media.jai.RenderedOp.createInstance(RenderedOp.java:830)
            at javax.media.jai.RenderedOp.createRendering(RenderedOp.java:878)
            at javax.media.jai.RenderedOp.getRendering(RenderedOp.java:899)
            at krakersupdater.PhotoProcessor.resizePhoto(PhotoProcessor.java:181)
            at krakersupdater.PhotoProcessor.doInBackground(PhotoProcessor.java:92)
            at krakersupdater.PhotoProcessor.doInBackground(PhotoProcessor.java:33)
            at javax.swing.SwingWorker$1.call(SwingWorker.java:278)
            at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
            at java.util.concurrent.FutureTask.run(FutureTask.java:138)
            at javax.swing.SwingWorker.run(SwingWorker.java:317)
            at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
            at java.lang.Thread.run(Thread.java:619)
    Caused by: java.lang.OutOfMemoryError: Java heap space
            at java.awt.image.DataBufferInt.<init>(DataBufferInt.java:41)
            at java.awt.image.Raster.createPackedRaster(Raster.java:458)
            at sun.awt.image.codec.JPEGImageDecoderImpl.allocateDataBuffer(JPEGImageDecoderImpl.java:338)
            at sun.awt.image.codec.JPEGImageDecoderImpl.readJPEGStream(Native Method)
            at sun.awt.image.codec.JPEGImageDecoderImpl.decodeAsBufferedImage(JPEGImageDecoderImpl.java:210)
            at com.sun.media.jai.codecimpl.JPEGImage.<init>(JPEGImageDecoder.java:114)
            at com.sun.media.jai.codecimpl.JPEGImageDecoder.decodeAsRenderedImage(JPEGImageDecoder.java:53)
            at com.sun.media.jai.opimage.CodecRIFUtil.create(CodecRIFUtil.java:120)
            at com.sun.media.jai.opimage.JPEGRIF.create(JPEGRIF.java:52)
            at sun.reflect.GeneratedMethodAccessor4.invoke(Unknown Source)
            at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
            at java.lang.reflect.Method.invoke(Method.java:597)
            at javax.media.jai.FactoryCache.invoke(FactoryCache.java:130)
            at javax.media.jai.OperationRegistry.invokeFactory(OperationRegistry.java:1682)
            at javax.media.jai.ThreadSafeOperationRegistry.invokeFactory(ThreadSafeOperationRegistry.java:481)
            at javax.media.jai.registry.RIFRegistry.create(RIFRegistry.java:340)
            at com.sun.media.jai.opimage.StreamRIF.create(StreamRIF.java:110)
            at sun.reflect.GeneratedMethodAccessor4.invoke(Unknown Source)
            at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
            at java.lang.reflect.Method.invoke(Method.java:597)
            at javax.media.jai.FactoryCache.invoke(FactoryCache.java:130)
            at javax.media.jai.OperationRegistry.invokeFactory(OperationRegistry.java:1682)
            at javax.media.jai.ThreadSafeOperationRegistry.invokeFactory(ThreadSafeOperationRegistry.java:481)
            at javax.media.jai.registry.RIFRegistry.create(RIFRegistry.java:340)
            at javax.media.jai.RenderedOp.createInstance(RenderedOp.java:830)
            at javax.media.jai.RenderedOp.createRendering(RenderedOp.java:878)
            at javax.media.jai.RenderedOp.getRendering(RenderedOp.java:899)
            at krakersupdater.PhotoProcessor.resizePhoto(PhotoProcessor.java:181)
            at krakersupdater.PhotoProcessor.doInBackground(PhotoProcessor.java:92)
            at krakersupdater.PhotoProcessor.doInBackground(PhotoProcessor.java:33)
            at javax.swing.SwingWorker$1.call(SwingWorker.java:278)
            at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)Why I cannot resize some photos ? It is because of color space ? If so, how can I convert from one color space to another ?
    This is link to photo which my function cannot handle: http://www.tvksmp.pl/~filipb/MULSUEEKR0006_LRG.jpg
    Edited by: CheckRaise on Aug 7, 2009 5:43 AM
    Edited by: CheckRaise on Aug 7, 2009 5:47 AM

    I was using ImageIO earlier for resizing but then got problems with jpg in another color spaceYou can save a JPEG in CMYK color space. The JPEGImageReader in core java is unable to read such jpegs, and will throw an IOException complaining that it can't. Although JAI won't throw an exception, it to isn't able to properly read the jpeg. JAI interprets cmyk images as argb images and the colors get all screwed up.
    And why this function consumes so much memory?What's the size of the largest image you are reading? And to what size are you scaling it?

  • Resizing jpegs

    I'm trying to make a simple program to resize jpegs and save them at a specified size but I'm not sure how I should be going about it. If anyone could give me any pointers it would be greatly apreciated. Thanks, Tom.

    You should have a look at the Java 2D API: http://java.sun.com/products/java-media/
    Here's a quick-and-dirty example program to create thumbnail images, it reads a source image and creates a thumbnail image. Works with any file type that your Java runtime environment supports (not just JPEG).
    import java.awt.geom.AffineTransform;
    import java.awt.image.AffineTransformOp;
    import java.awt.image.BufferedImage;
    import java.awt.image.BufferedImageFilter;
    import java.io.File;
    import javax.imageio.ImageIO;
    public class Thumbnail {
        public static void main(String[] args) throws Exception {
            double targetWidth  = 200.0;
            double targetHeight = 150.0;
            // Read source image
            BufferedImage src = ImageIO.read(new File(args[0]));
            double scale;
            int width = src.getWidth();
            int height = src.getHeight();
            if (width > height) {
                // Landscape orientation
                scale = targetWidth / width;
                if (scale * height > targetHeight) {
                    scale = targetHeight / height;
            else {
                // Portrait orientation
                scale = targetWidth / height;
                if (scale * width > targetHeight) {
                    scale = targetHeight / width;
            AffineTransform trans = new AffineTransform();
            trans.setToScale(scale, scale);
            AffineTransformOp op = new AffineTransformOp(trans, AffineTransformOp.TYPE_NEAREST_NEIGHBOR);
            BufferedImage dest = op.createCompatibleDestImage(src, null);
            op.filter(src, dest);
            // Write result image
            String outputFormat = args[1].substring(args[1].length() - 3);
            ImageIO.write(dest, outputFormat, new File(args[1]));
    }Jesper

  • Resizing, renaming images...

    Okay, maybe Java isnt the solution for this, but I figured I'd check it out.
    I'ma photogenic person, I love my digital camera to death but I have a problem... When I take the images off my camera they're like 2200px by 1800px or something to that effect, way to large. So I immediately open them in photoshop, resize them, and save/rename them. It's rather tedious. So I'm looking to write an application, preferably in java, that I will enter in a directory (c:\dir\blah\blah) and it takes all the images in there and resizes them to say 600x400px and bumps the quality down from 10 to 7 (photoshop talk there, heh) then saves them.
    Is Java best for this situation, if so, can anyone push me into the right direction?

    It can be done with java.
    I wrote a hobby application to generate thumb-views (and extract exif data) into a separate directory. It is written in Java including the thumb-views' resizing from the original images. I used code snippets (for resizing) and an exif package found in the internet - see the comment in the code.
    If I had your address, I could mail the whole stuff to you.
    Beware however the spammers' e-mail-sniffing bots!
    As said it was a hobby project. But you do not need to reinvent the wheel.
    Image Magic(k) has ready-made tools (convert.exe) for this purpose, you only need to write some launcher script. Or some image viewers could provide a GUI interface to this batch-like activity, maybe Irfanview too.
    http://www.imagemagick.org/script/index.php
    http://www.irfanview.com/
    package hu.bij.thwutil;
    //http://blog.cyberjos.idv.tw/space/Esaily+scale+image+in+Java
    import java.awt.Graphics2D;
    import java.awt.image.BufferedImage;
    import java.io.File;
    import javax.imageio.ImageIO;
    import javax.swing.JFrame;
    public class SImage
      public static final String    JPEG = "jpg";
      public static final String    PNG = "png";
      private int                   srcHeight = 0;
      private int                   srcWidth = 0;
      private int                   height = 0;
      private int                   width = 0;
      private double                scale = 0.0;
      private boolean               resized = false;
      private BufferedImage         bimage;
      public SImage( String filename )  throws Exception
        this( filename, 1.0 );
      public SImage( BufferedImage aimage, double scale ) throws Exception
        bimage = aimage;
        srcHeight = bimage.getHeight();
        srcWidth = bimage.getWidth();
        setScale( scale );
      public SImage( String filename, double scale ) throws Exception
        this(ImageIO.read(new File( filename)),scale);
      public void write(String filename, String format ) throws Exception
         write(new File(filename),format);
      public void write( File output, String format ) throws Exception
        BufferedImage       bimage2 = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB );
        Graphics2D          g2d = ( Graphics2D ) bimage2.getGraphics();
        if ( resized )
          g2d.scale( ( double ) width / srcWidth, ( double ) height / srcHeight );
        else
          g2d.scale( scale, scale );
        g2d.drawImage( bimage, 0, 0, new JFrame() );
        ImageIO.write( bimage2, format, output );
      public void resize( int width, int height )
        if ( width < 1 )
          width = 1;
        if ( height < 1 )
          height = 1;
        this.width = width;
        this.height = height;
        resized = true;
      public boolean isResized()
        return resized;
      public double getScale()
        if ( resized )
          return 0.0;
        return scale;
      public void setScale( double scale )
        if ( scale < 0.01 )
          scale = 0.01;
        else if ( scale > 16.0 )
          scale = 16.0;
        this.scale = scale;
        height = ( int ) ( srcHeight * scale );
        width = ( int ) ( srcWidth * scale );
        resized = false;
      public int getHeight()
        return height;
      public int getWidth()
        return width;
      public int getSrcHeight()
        return srcHeight;
      public int getSrcWidth()
        return srcWidth;
      public static void main( String args[] ) throws Exception
        if ( args.length != 3 )
          System.out.println( "Usage: java ImageScale [src] [dest] [rate]" );
          System.exit( 0 );
        SImage      image = new SImage( args[ 0 ], Double.parseDouble( args[ 2 ] ) );
        image.write( args[ 1 ], SImage.JPEG );
        image.setScale( 0.5 );
        image.write( "1" + args[ 1 ], SImage.PNG );
        image.resize( image.getWidth() + 300, image.getHeight() + 100 );
        image.write( "2" + args[ 1 ], SImage.JPEG );
    }

Maybe you are looking for

  • Error in module RSQL of the database interface.

    Hi Expert, I get this error "Error in module RSQL of the database interface." when the below ABAP statement executed,  do you know the root cuase? Thanks. ABAP Code:   data lt_fact type TABLE OF /BIC/FZRT_C002.   data ls_Fact type /BIC/FZRT_C002.   *

  • New magic mouse

    Don't know where to go. With the new mouse how do I go about copy and paste. I usually hi-lite, press the left and a menu came down to "copy" Can't seem to do that with the new mouse?

  • Using Java Advanced Imaging (JAI) in Applet

    I'm trying to port a JAI user interface to an applet using Apache Tomcat. When I try to display an image in the applet I get an exception and I have no idea what the cause is. I've opened up security completely (temporarily) to ensure that I'm not ge

  • Can't install 9i on XP

    Hi, I hope someone can help. I am taking a class that requires us to use 9i. I downloaded and extracted the files with the disk1, 2, 3 directories. When I go to disk1 and click on the setup icon, nothing happens. Do I need to do anything else? The ic

  • Extra thin white rule showing up outside a frame.

    Hello, Well, I thought this would be easy, but I can't seem to find where to turn this off. I was looking at a clients file and there is an additional very thin white rule, that sits just outside the actual frame when selected. It's not a frame edge?