How To Resize Uploaded Images Using Java – Better Way

Based on helpful comments from Matt on this previous post:

How To Resize Uploaded Images Using Java

I have upgraded the image resizing code. The results are noticeably better in quality, even at thumbnail sizes. I wanted to share the completed new code, in case anyone needs it.

Again, thanks to Matt S. for his pointers.

[fusion_builder_container hundred_percent=”yes” overflow=”visible”][fusion_builder_row][fusion_builder_column type=”1_1″ background_position=”left top” background_color=”” border_size=”” border_color=”” border_style=”solid” spacing=”yes” background_image=”” background_repeat=”no-repeat” padding=”” margin_top=”0px” margin_bottom=”0px” class=”” id=”” animation_type=”” animation_speed=”0.3″ animation_direction=”left” hide_on_mobile=”no” center_content=”no” min_height=”none”][java]
/**
* The JAI.create action name for handling a stream.
*/
private static final String JAI_STREAM_ACTION = “stream”;

/**
* The JAI.create action name for handling a resizing using a subsample averaging technique.
*/
private static final String JAI_SUBSAMPLE_AVERAGE_ACTION = “SubsampleAverage”;

/**
* The JAI.create encoding format name for JPEG.
*/
private static final String JAI_ENCODE_FORMAT_JPEG = “JPEG”;

/**
* The JAI.create action name for encoding image data.
*/
private static final String JAI_ENCODE_ACTION = “encode”;

/**
* The http content type/mime-type for JPEG images.
*/
private static final String JPEG_CONTENT_TYPE = “image/jpeg”;

private int mMaxWidth = 800;

private int mMaxWidthThumbnail = 150;

…..

/**
* This method takes in an image as a byte array (currently supports GIF, JPG, PNG and
* possibly other formats) and
* resizes it to have a width no greater than the pMaxWidth parameter in pixels.
* It converts the image to a standard
* quality JPG and returns the byte array of that JPG image.
*
* @param pImageData
* the image data.
* @param pMaxWidth
* the max width in pixels, 0 means do not scale.
* @return the resized JPG image.
* @throws IOException
* if the image could not be manipulated correctly.
*/
public byte[] resizeImageAsJPG(byte[] pImageData, int pMaxWidth) throws IOException {
InputStream imageInputStream = new ByteArrayInputStream(pImageData);
// read in the original image from an input stream
SeekableStream seekableImageStream = SeekableStream.wrapInputStream(imageInputStream, true);
RenderedOp originalImage = JAI.create(JAI_STREAM_ACTION, seekableImageStream);
((OpImage) originalImage.getRendering()).setTileCache(null);
int origImageWidth = originalImage.getWidth();
// now resize the image
double scale = 1.0;
if (pMaxWidth > 0 && origImageWidth > pMaxWidth) {
scale = (double) pMaxWidth / originalImage.getWidth();
}
ParameterBlock paramBlock = new ParameterBlock();
paramBlock.addSource(originalImage); // The source image
paramBlock.add(scale); // The xScale
paramBlock.add(scale); // The yScale
paramBlock.add(0.0); // The x translation
paramBlock.add(0.0); // The y translation

RenderingHints qualityHints = new RenderingHints(RenderingHints.KEY_RENDERING,
RenderingHints.VALUE_RENDER_QUALITY);

RenderedOp resizedImage = JAI.create(JAI_SUBSAMPLE_AVERAGE_ACTION, paramBlock, qualityHints);

// lastly, write the newly-resized image to an output stream, in a specific encoding
ByteArrayOutputStream encoderOutputStream = new ByteArrayOutputStream();
JAI.create(JAI_ENCODE_ACTION, resizedImage, encoderOutputStream, JAI_ENCODE_FORMAT_JPEG, null);
// Export to Byte Array
byte[] resizedImageByteArray = encoderOutputStream.toByteArray();
return resizedImageByteArray;
}

[/java]

[/fusion_builder_column][/fusion_builder_row][/fusion_builder_container]


Posted

in

,

by

Comments

61 responses to “How To Resize Uploaded Images Using Java – Better Way”

  1. Maeve Avatar
    Maeve

    Hi!
    Thanks for this code! I tried many different code-pieces, but yours was the only one which worked.
    The result looks good too. =)
    Greetings, Maeve

  2. Mike McP Avatar
    Mike McP

    I’m trying to test out this improved version in an existing app I have, and I’m getting this error when I run it:

    Exception in thread “AgentThread: JavaAgent” java.lang.NoClassDefFoundError: com.sun.media.jai.codec.SeekableStream
    at com.lekkimworld.lotusphere2007.picture_importer.PictureImporter.resizeImageAsJPG(PictureImporter.java:111)
    at com.lekkimworld.lotusphere2007.picture_importer.PictureImporter.importPicture(PictureImporter.java:326)
    at JavaAgent.NotesMain(JavaAgent.java:19)
    at lotus.domino.AgentBase.runNotes(Unknown Source)
    at lotus.domino.NotesThread.run(Unknown Source)

    In Eclipse, I’ve referenced jai_codec.jar and jai_core.jar, and I verified that they exist where their paths point on my file system. Any ideas what the cause of this could be? I’m anxious to test the quality of this improved version over my homebrew code (very similar to Devon’s first posting on the topic).

    take care, Mike

  3. Devon Avatar

    Mike:

    it compiles in Eclipse I assume, and just throws this error during runtime? You should check the classpath for the running app and ensure the jai_codec.jar is in the classpath of the app (outside of eclipse).

    Just my initial thoughts…

  4. Mike McP Avatar
    Mike McP

    Ahh, you’re completely correct…this was my dumb mistake! I’m running this app in Lotus Notes, and I forgot to move the jai JAR files over to my running app! Thanks Devon…works like a charm, and much better quality than my earlier code!

    take care,
    MIke

  5. Devon Avatar

    Mike: Glad to hear it!! I was very impressed with the image quality of this updated code. I’m glad it’s worked out for you as well.

  6. Matthias Avatar

    JPEG_CONTENT_TYPE should be just “JPG” instead of “image/jpeg”. The spec does not expect a MIME type, but one of:

    BMP
    JPEG
    PNG
    PNM
    TIFF
    See http://java.sun.com/products/java-media/jai/forDevelopers/jai1_0_1guide-unc/Encode.doc.html#56610

    I noticed because using “image/png” instead threw an exception, but “png” worked. That is for JAI 1.1.3.

  7. Devon Avatar

    @Matthias: The encoder call is actually using the JAI_ENCODE_FORMAT_JPEG constant, which has a value of “JPEG”. The JPEG_CONTENT_TYPE constant isn’t used in that code snippet, but it used elsewhere in the class I copied the code from to set mime type headers into the database record for the file metadata.

  8. Newbie Avatar
    Newbie

    Iam new to JAI and i tried using the code snipped provided here to resize an image.I get the following exception:
    java.lang.RuntimeException: – Unable to render RenderedOp for this operation.
    Pls let me know wht could be the reason for the same

  9. Devon Avatar

    @Newbie: perhaps the image format isn’t supported by the codecs in JAI? What is the image format you are working with? Can you share the full stack trace of the error?

    Thanks!

  10. Andy Westley Avatar
    Andy Westley

    I just wanted to say that having tried some really horrible messy code to integrate apache commons fileupload and some awt-based image resizing code, I stumbled across your artice, and the code dropped into my project seamlessly. Brilliant.

    1. Devon Avatar

      Andy,

      I’m very glad that my post was helpful!

      Devon

  11. Kris Avatar
    Kris

    I’ve found that when I need to scale a large image down to less than 50% of the original size, this method works GREAT! However, when (0.5d <= scale < 1.0d) this really didn’t produce very good images for me. I had to modify the code to resize using up to three different methods depending on the value of scale. See the code I’ve provided here:
    http://pastebin.com/f13fbbfb3

    I welcome any feedback!

    1. Devon Avatar

      Kris: very cool! The code looks great, and I’ll have to try it out!

      Thanks again!

      Devon

  12. Adrian Avatar
    Adrian

    Devon,

    I like your work here. One question (and maybe I just missed reading up on it on your article(s)), any idea on what I can do to deal with images that have transparencies? GIF in particular.

    Thanks in advance,

    Adrian

    1. Devon Avatar

      Adrian:

      I haven’t dealt with transparent images with this code, so it will probably need some modification. There’s some useful code here:

      http://stackoverflow.com/questions/244164/resize-an-image-in-java-any-open-source-library/244177

      And I’ve also seen some good pages when Googling for “JAI transparency” and “JAI alpha”

      If you build some working code that supports GIF and PNGs with transparencies, could you please post it here, or link to your own posting of it?

      Thanks!

      Devon

      1. Adrian Avatar
        Adrian

        Will do… thanks for that link…

  13. NewBie2JAI Avatar
    NewBie2JAI

    Hi Devon,

    I am another Newbie to JAI and I too get the same exception as Newbie. My stack trace as below:

    Exception in thread “main” java.lang.RuntimeException: – Unable to render RenderedOp for this operation.
    at javax.media.jai.RenderedOp.createInstance(RenderedOp.java:826)
    at javax.media.jai.RenderedOp.createRendering(RenderedOp.java:866)
    at javax.media.jai.RenderedOp.getRendering(RenderedOp.java:887)
    at testfiles.ResizeImage.resizeImageAsJPG(ResizeImage.java:89)
    at testfiles.ResizeImage.main(ResizeImage.java:30)

    I call your method as below in main method of a standalone java class:

    try{
    File file = new File(“C:\\Documents and Settings\\All Users\\Documents\\My Pictures\\Sample Pictures\\Blue hills.jpg”);
    long length = file.length();
    byte[] bytes = new byte[(int)length];
    new ResizeImage().resizeImageAsJPG(bytes, 20);
    }catch (IOException e) {
    e.printStackTrace();
    }

    Please let me know where I am going wrong.

    1. Devon Avatar

      @NewBie2JAI:

      unless you’ve left out some of your code, the problem is that you aren’t loading the image file into the byte array before you call the resize method. You initialize the byte array, but do not load the data into it.

      There is a basic example of how to do this here:

      http://www.exampledepot.com/egs/java.io/File2ByteArray.html

      I hope that helps!

  14. NewBie2JAI Avatar
    NewBie2JAI

    Well on loading data into byte array as in the example link I get the following error:

    Error: Could not find mediaLib accelerator wrapper classes. Continuing in pure Java mode.
    Occurs in: com.sun.media.jai.mlib.MediaLibAccessor
    java.lang.NoClassDefFoundError: com/sun/medialib/mlib/Image
    at com.sun.media.jai.mlib.MediaLibAccessor$1.run(MediaLibAccessor.java:248)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.media.jai.mlib.MediaLibAccessor.setUseMlib(MediaLibAccessor.java:245)
    at com.sun.media.jai.mlib.MediaLibAccessor.useMlib(MediaLibAccessor.java:177)
    at com.sun.media.jai.mlib.MediaLibAccessor.isMediaLibCompatible(MediaLibAccessor.java:357)
    at com.sun.media.jai.mlib.MediaLibAccessor.isMediaLibCompatible(MediaLibAccessor.java:315)
    at com.sun.media.jai.mlib.MlibSubsampleAverageRIF.create(MlibSubsampleAverageRIF.java:56)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at javax.media.jai.FactoryCache.invoke(FactoryCache.java:122)
    at javax.media.jai.OperationRegistry.invokeFactory(OperationRegistry.java:1674)
    at javax.media.jai.ThreadSafeOperationRegistry.invokeFactory(ThreadSafeOperationRegistry.java:473)
    at javax.media.jai.registry.RIFRegistry.create(RIFRegistry.java:332)
    at javax.media.jai.RenderedOp.createInstance(RenderedOp.java:818)
    at javax.media.jai.RenderedOp.createRendering(RenderedOp.java:866)
    at javax.media.jai.RenderedOp.getRendering(RenderedOp.java:887)
    at javax.media.jai.RenderedOp.createInstance(RenderedOp.java:798)
    at javax.media.jai.RenderedOp.createRendering(RenderedOp.java:866)
    at javax.media.jai.RenderedOp.getRendering(RenderedOp.java:887)
    at javax.media.jai.JAI.createNS(JAI.java:1099)
    at javax.media.jai.JAI.create(JAI.java:973)
    at javax.media.jai.JAI.create(JAI.java:1668)
    at testfiles.ResizeImage.resizeImageAsJPG(ResizeImage.java:146)
    at testfiles.ResizeImage.main(ResizeImage.java:38)
    Caused by: java.lang.ClassNotFoundException: com.sun.medialib.mlib.Image
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClassInternal(Unknown Source)
    … 26 more

    Its breaking at this point in the resizeImageAsJPG which is line 146

    JAI.create(JAI_ENCODE_ACTION, resizedImage, encoderOutputStream, JAI_ENCODE_FORMAT_JPEG, null);

    Anything I missed?

    1. Antigen Avatar
      Antigen

      You can turn off acceleration :

      static {
      System.setProperty(“com.sun.media.jai.disableMediaLib”, “true”);
      }

      1. phuongdeptrai Avatar
        phuongdeptrai

        Great! Thank you! Thank you! Thank you! Thank you! Thank you! Thank you! Thank you! Thank you! Thank you! Thank you! Thank you! ….

  15. NewBie2JAI Avatar
    NewBie2JAI

    Hey Devon…. I got it working… found the missing library file “mlibwrapper_jai”.

    1. Devon Avatar

      Great! I’m glad to hear it!

  16. […] Edit: please read the better way here: Better way to Resize Images Using Java! […]

  17. NewBie2JAI Avatar
    NewBie2JAI

    Hi Devon,

    Is there a better way to crop images vertically to a specific height for specific widths if the height is beyond certain limit. For e.g.
    if the resized image’s width is 160 px and its height is beyond 200px than it should be cropped vertically upto 200 px in height. The cropping should be proportionate from top as well as bottom and retain the center portion of the resized image as is. Appreciate your help.

    1. Devon Avatar

      NewBie2JAI: a quick googling for “JAI crop image” gave some good results. This code snippet looks promising, but I’d definitely google for it and read the docs on the JAI “crop” action.

      RenderedImage ri = JAI.create(“fileload”,pathandfilename);

      public void crop()
      {
      pb = new ParameterBlock();
      pb.addSource(ri);
      pb.add((float)topLeftmx);
      pb.add((float)topLeftmy);
      pb.add((float)roiWidth);
      pb.add((float)roiHeight);
      ri = JAI.create(“crop”,pb);
      }

      1. Anamika Avatar
        Anamika

        can u send me a core java project on “image editor” ..??
        plzz help its very urgent..
        thanks!!

        1. Devon Avatar

          I don’t understand what you are asking for?

  18. NewBie2JAI Avatar
    NewBie2JAI

    Thanks Devon. I too googled it out and impemented it but I am getting this error:”Crop The rectangular crop area must not be outside the image.” Working on it.. Thanks though.

    1. Devon Avatar

      Is it possible your crop dimensions are larger than the image dimensions? That’s what the error sounds like to me.

  19. NewBie2JAI Avatar
    NewBie2JAI

    FYI..

    I am using “ParameterBlockJAI” and setting the parameters for minX, minY and width, height.

  20. Jean-Marie Tinghir Avatar
    Jean-Marie Tinghir

    I had very bad quality resized images, and it appeared that the solution was to specify the interpolation.
    The default is the InterpolationNearest, but the InterpolationBilinear or InterpolationBicubic give much better quality.
    But then there was an other problem with those interpolations : black borders sometimes appear after scale operation.
    So I had to scale it with 2 more pixels, and then crop it with x=1 y=1 and the size I want.

  21. shiva Avatar
    shiva

    This code looks great. But i am facing one small (small??? or big???) issue. I am getting this exception. can you please show me the way on this

    java.lang.IllegalArgumentException: SubsampleAverage: No OperationDescriptor is registered in the current operation registry under this name.
    at javax.media.jai.JAI.createNS(Ljava/lang/String;Ljava/awt/image/renderable/ParameterBlock;Ljava/awt/RenderingHints;)Ljavax/media/jai/RenderedOp;(JAI.java:883)
    at javax.media.jai.JAI.create(Ljava/lang/String;Ljava/awt/image/renderable/ParameterBlock;Ljava/awt/RenderingHints;)Ljavax/media/jai/RenderedOp;(JAI.java:786)

    1. Devon Avatar

      My guess is that you’re missing some JAI jars on your classpath?

  22. Benjamin Avatar
    Benjamin

    I have this problem, when the code it’s executed in a machine with Linux, and if the file is a GIF

    java.lang.RuntimeException: – Unable to render RenderedOp for this operation.
    at javax.media.jai.RenderedOp.createInstance(RenderedOp.java:827)
    at javax.media.jai.RenderedOp.createRendering(RenderedOp.java:867)
    at javax.media.jai.RenderedOp.getWidth(RenderedOp.java:2179)

    Any ideas?

    1. Devon Avatar

      Benjamin,

      my only guess is perhaps it’s something like what an above commenter had: http://172.31.20.105/tech-blog/java/how-to-resize-uploaded-images-using-java-better-way.html/comment-page-1#comment-42050

      Can you provide the code you’re calling my code with?

      Does your code work with other file types or on other operating systems?

      Thanks!

      Devon

      1. Benjamin Avatar
        Benjamin

        Hi Devon,

        We resolved the issue.

        Thanks.

  23. Nix4J Avatar
    Nix4J

    Guys,

    Let me congratulate everyone on doing an extremely wonderful job here.

    I have been working on a TIFF document viewe/editor (applet+JAI) piece.

    It provides zoom and rotate functionality using the “scale” and “transpose” operators on JAI.create(). Now my applet is signed and I have JAI installed on the client machine (jai_imageio.jar, jai_core.jar, jai_codec.jar) in the JRE/lib/ext folder.

    The applets loads fine, downloading my applet JAR, and the TIFF document is retrieved from the server and displayed in the applet, within the browser. I use javascript buttons to call on the applet functions to zoom and rotate.

    ROTATE CODE
    —————————————
    ParameterBlock pb = new ParameterBlock();
    pb.addSource(image);
    pb.add(TransposeDescriptor.ROTATE_90); //assume I always rotate by 90 degrees
    RenderedOp rotatedImage = JAI.create(“transpose”, pb);

    ZOOM CODE:
    ——————————————
    ParameterBlock pb = new ParameterBlock();
    pb.addSource(image);
    pb.add((float)magFactor);
    pb.add((float)magFactor);
    pb.add(0.0F);
    pb.add(0.0F);
    RenderedImage scaledImage = JAI.create(“scale”, pb, null);

    ——————————————————-

    I am getting the following exceptions for Zoom and Rotate respectively

    ZOOM EXCEPTION
    ——————————————————-
    java.lang.reflect.InvocationTargetException

    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)

    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)

    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)

    at java.lang.reflect.Method.invoke(Unknown Source)

    at gov.wisconsin.viewer.framework.controller.AbstractControllerApplet.invokeService(AbstractControllerApplet.java:83)

    at gov.wisconsin.viewer.framework.controller.AbstractControllerApplet.perform(AbstractControllerApplet.java:106)

    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)

    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)

    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)

    at java.lang.reflect.Method.invoke(Unknown Source)

    at sun.plugin.javascript.invoke.JSInvoke.invoke(Unknown Source)

    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)

    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)

    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)

    at java.lang.reflect.Method.invoke(Unknown Source)

    at sun.plugin.javascript.JSClassLoader.invoke(Unknown Source)

    at sun.plugin.com.MethodDispatcher.invoke(Unknown Source)

    at sun.plugin.com.DispatchImpl.invokeImpl(Unknown Source)

    at sun.plugin.com.DispatchImpl$1.run(Unknown Source)

    at java.security.AccessController.doPrivileged(Native Method)

    at sun.plugin.com.DispatchImpl.invoke(Unknown Source)

    Caused by: java.lang.ExceptionInInitializerError

    at gov.wisconsin.viewer.management.TiffManager.magnifyAndShow(TiffManager.java:240)

    at gov.wisconsin.viewer.management.TiffManager.zoom(TiffManager.java:266)

    … 21 more

    Caused by: java.security.AccessControlException: access denied (java.lang.RuntimePermission modifyThreadGroup)

    at java.security.AccessControlContext.checkPermission(Unknown Source)

    at java.security.AccessController.checkPermission(Unknown Source)

    at java.lang.SecurityManager.checkPermission(Unknown Source)

    at sun.applet.AppletSecurity.checkAccess(Unknown Source)

    at java.lang.ThreadGroup.checkAccess(Unknown Source)

    at java.lang.ThreadGroup.(Unknown Source)

    at java.lang.ThreadGroup.(Unknown Source)

    at com.sun.media.jai.util.SunTileScheduler.(SunTileScheduler.java:689)

    at javax.media.jai.JAI.(JAI.java:560)

    … 23 more

    ROTATE EXCEPTION
    ——————————————————-

    java.lang.reflect.InvocationTargetException

    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)

    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)

    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)

    at java.lang.reflect.Method.invoke(Unknown Source)

    at gov.wisconsin.viewer.framework.controller.AbstractControllerApplet.invokeService(AbstractControllerApplet.java:83)

    at gov.wisconsin.viewer.framework.controller.AbstractControllerApplet.perform(AbstractControllerApplet.java:106)

    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)

    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)

    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)

    at java.lang.reflect.Method.invoke(Unknown Source)

    at sun.plugin.javascript.invoke.JSInvoke.invoke(Unknown Source)

    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)

    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)

    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)

    at java.lang.reflect.Method.invoke(Unknown Source)

    at sun.plugin.javascript.JSClassLoader.invoke(Unknown Source)

    at sun.plugin.com.MethodDispatcher.invoke(Unknown Source)

    at sun.plugin.com.DispatchImpl.invokeImpl(Unknown Source)

    at sun.plugin.com.DispatchImpl$1.run(Unknown Source)

    at java.security.AccessController.doPrivileged(Native Method)

    at sun.plugin.com.DispatchImpl.invoke(Unknown Source)

    Caused by: java.lang.ExceptionInInitializerError

    at gov.wisconsin.viewer.management.TiffManager.rotate(TiffManager.java:337)

    … 21 more

    Caused by: java.security.AccessControlException: access denied (java.lang.RuntimePermission modifyThreadGroup)

    at java.security.AccessControlContext.checkPermission(Unknown Source)

    at java.security.AccessController.checkPermission(Unknown Source)

    at java.lang.SecurityManager.checkPermission(Unknown Source)

    at sun.applet.AppletSecurity.checkAccess(Unknown Source)

    at java.lang.ThreadGroup.checkAccess(Unknown Source)

    at java.lang.ThreadGroup.(Unknown Source)

    at java.lang.ThreadGroup.(Unknown Source)

    at com.sun.media.jai.util.SunTileScheduler.(SunTileScheduler.java:689)

    at javax.media.jai.JAI.(JAI.java:560)

    … 22 more

    ———————————————————

    Both exceptions trace down to the line where I use JAI.create() method for scale or rotate. I thought by signing the jar all access exceptions would be resolved. But it seems I am still getting “Caused by: java.security.AccessControlException: access denied” exceptions.

    Now I am not sure what am I doing wrong. Is there anything special that I need to do within applet in order to get the JAI.create() method to work?

    Any feedback, pointers, help would be very appreciated !

    Regards,
    Nix4J

  24. Rabbit Avatar
    Rabbit

    Hi, I have followed your method to do my image scaling & resizing. It works well for jpegs and some png files, but I am having a problem with transparent gifs and some png files. They come out pink in color. What could be the reason? (I have used your code as given above).

    1. Devon Avatar

      My guess is it’s related to transparency/alpha channel data, which I haven’t tested my code with. I’d recommend looking at the link in this comment: http://172.31.20.105/tech-blog/java/how-to-resize-uploaded-images-using-java-better-way.html/comment-page-1#comment-41629

      Which might help!

      Devon

  25. dugout Avatar
    dugout

    hi i have a question..
    How do i use this code if i have a 100×100 jpg and i want to transform it in a 400×400 jpg?Please help me

    1. Devon Avatar

      Dugout,

      you’ll need to change the logic in lines 55-58 to allow for upscaling. You may also want to change the sub sample average action to provide better quality when uprezing the images.

      Otherwise the code should work for what you want.

    1. Devon Avatar

      Jagan,

      I get a 404 when trying to access that image. What is the exception and stacktrace of the error?

      1. Jagan Avatar

        exception

        java.lang.RuntimeException: – Unable to render RenderedOp for this operation.
        at javax.media.jai.RenderedOp.createInstance(RenderedOp.java:827)
        at javax.media.jai.RenderedOp.createRendering(RenderedOp.java:867)
        at javax.media.jai.RenderedOp.getRendering(RenderedOp.java:888)
        at com.styleretail.servlets.ImageDisplay.doGet(ImageDisplay.java:83)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:690)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
        at org.jboss.web.tomcat.filters.ReplyHeaderFilter.doFilter(ReplyHeaderFilter.java:96)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
        at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:235)
        at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
        at org.jboss.web.tomcat.security.SecurityAssociationValve.invoke(SecurityAssociationValve.java:189)
        at org.jboss.web.tomcat.security.JaccContextValve.invoke(JaccContextValve.java:91)
        at org.jboss.web.tomcat.security.SecurityContextEstablishmentValve.invoke(SecurityContextEstablishmentValve.java:92)
        at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
        at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
        at org.jboss.web.tomcat.service.jca.CachedConnectionValve.invoke(CachedConnectionValve.java:157)
        at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
        at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:325)
        at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:828)
        at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:601)
        at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447)
        at java.lang.Thread.run(Thread.java:595)

      2. Jagan Avatar

        I am also getting exception with following type image http://www.designershoes.com/media/shoes_300/4/0/40291SA_1.jpg

        1. Devon Avatar

          Jagan,

          I *think* the issue is that the image is a JPG using the CMYK color model, not the typical (for JPGs anyhow) RGB one. You can read more about the hoops you’ll need to jump though to support CMYK based images here: http://stackoverflow.com/questions/2408613/problem-reading-jpeg-image-using-imageio-readfile-file

          Devon

  26. Glen Avatar
    Glen

    I got this error, can someone help me to prevent this error please?
    Error: One factory fails for the operation “encode”
    Occurs in: javax.media.jai.ThreadSafeOperationRegistry
    java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at javax.media.jai.FactoryCache.invoke(Unknown Source)
    at javax.media.jai.OperationRegistry.invokeFactory(Unknown Source)
    at javax.media.jai.ThreadSafeOperationRegistry.invokeFactory(Unknown Source)
    at javax.media.jai.registry.RIFRegistry.create(Unknown Source)
    at javax.media.jai.RenderedOp.createInstance(Unknown Source)
    at javax.media.jai.RenderedOp.createRendering(Unknown Source)
    at javax.media.jai.RenderedOp.getRendering(Unknown Source)
    at javax.media.jai.JAI.createNS(Unknown Source)
    at javax.media.jai.JAI.create(Unknown Source)
    at javax.media.jai.JAI.create(Unknown Source)
    at images.ImageForm.resizeImageAsJPG(ImageForm.java:103)
    at images.ImageForm.customInit(ImageForm.java:68)
    at images.ImageForm.(ImageForm.java:61)
    at images.Main.main(Main.java:17)
    Caused by: java.lang.IllegalArgumentException: Requested rectangle bounds is not contained in the input raster`s bounds.
    at javax.media.jai.RasterAccessor.(Unknown Source)
    at com.sun.media.jai.opimage.SubsampleAverageOpImage.computeRect(Unknown Source)
    at javax.media.jai.GeometricOpImage.computeTile(Unknown Source)
    at com.sun.media.jai.util.SunTileScheduler.scheduleTile(Unknown Source)
    at javax.media.jai.OpImage.getTile(Unknown Source)
    at javax.media.jai.PlanarImage.getData(Unknown Source)
    at javax.media.jai.PlanarImage.getData(Unknown Source)
    at com.sun.media.jai.codecimpl.JPEGImageEncoder.encode(JPEGImageEncoder.java:174)
    at com.sun.media.jai.opimage.EncodeRIF.create(Unknown Source)
    … 18 more

    1. Devon Avatar

      Glen,

      looks like you’re trying to do something using dimensions that are bigger than the image without upscaling?

      “Caused by: java.lang.IllegalArgumentException: Requested rectangle bounds is not contained in the input raster`s bounds.”

  27. […] up all sorts of examples of resizing images.  This blog in particular seemed to be a good start: Digital Sanctuary, and I got an example running […]

  28. Kristian Helgesen Avatar

    Hi all.

    Take a look at http://croputils.sourceforge.net/

    The project provides a simple utility class to do fast and good looking crop and downscaling of images.

    -Kristian

  29. Linh ??ng Avatar
    Linh ??ng

    I have trouble . Please help me :(
    Error: One factory fails for the operation “encode”
    Occurs in: javax.media.jai.ThreadSafeOperationRegistry
    java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at javax.media.jai.FactoryCache.invoke(Unknown Source)
    at javax.media.jai.OperationRegistry.invokeFactory(Unknown Source)
    at javax.media.jai.ThreadSafeOperationRegistry.invokeFactory(Unknown Source)
    at javax.media.jai.registry.RIFRegistry.create(Unknown Source)
    at javax.media.jai.RenderedOp.createInstance(Unknown Source)
    at javax.media.jai.RenderedOp.createRendering(Unknown Source)
    at javax.media.jai.RenderedOp.getRendering(Unknown Source)
    at javax.media.jai.JAI.createNS(Unknown Source)
    at javax.media.jai.JAI.create(Unknown Source)
    at javax.media.jai.JAI.create(Unknown Source)
    at hqbc.util.ImageResize.resizeImageAsJPG(ImageResize.java:61)
    at org.apache.jsp.admin.photo.add_005fresp_jsp._jspService(add_005fresp_jsp.java:141)
    at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
    at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:374)
    at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:342)
    at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:267)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293)
    at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:849)
    at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:583)
    at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:454)
    at java.lang.Thread.run(Thread.java:619)
    Caused by: java.lang.IllegalArgumentException: Requested rectangle bounds is not contained in the input raster`s bounds.
    at javax.media.jai.RasterAccessor.(Unknown Source)
    at com.sun.media.jai.opimage.SubsampleAverageOpImage.computeRect(Unknown Source)
    at javax.media.jai.GeometricOpImage.computeTile(Unknown Source)
    at com.sun.media.jai.util.SunTileScheduler.scheduleTile(Unknown Source)
    at javax.media.jai.OpImage.getTile(Unknown Source)
    at javax.media.jai.PlanarImage.getData(Unknown Source)
    at javax.media.jai.PlanarImage.getData(Unknown Source)
    at com.sun.media.jai.codecimpl.PNGImageEncoder.writeIDAT(PNGImageEncoder.java:446)
    at com.sun.media.jai.codecimpl.PNGImageEncoder.encode(PNGImageEncoder.java:1026)
    at com.sun.media.jai.opimage.EncodeRIF.create(Unknown Source)
    … 34 more

    1. Devon Avatar

      Are you trying to encode a TIFF? Buggy TIFF files will cause that. Please Google the error message: “Error: One factory fails for the operation “encode” Occurs in: javax.media.jai.ThreadSafeOperationRegistry”

  30. Dhana Avatar
    Dhana

    Please help me..

    Get an exception when trying to upload an image:

    Error: One factory fails for the operation “encode”
    Occurs in: javax.media.jai.ThreadSafeOperationRegistry

    Caused by: java.lang.IncompatibleClassChangeError: Found class
    com.sun.image.codec.jpeg.JPEGImageEncoder, but interface was expected
    at
    com.sun.media.jai.codecimpl.JPEGImageEncoder.encode(JPEGImageEncoder.java:215)
    at com.sun.media.jai.opimage.EncodeRIF.create(EncodeRIF.java:79)
    … 47 more

  31. monkey Avatar
    monkey

    Thanks you devon…

    people who got trouble or having unsuccessful program should pay attention whether you got “JAI” or not ..
    if you have not installed it yet.. you can get it from the following..
    http://download.java.net/media/jai/builds/release/1_1_3/

    and the following is the installation instruction
    http://download.java.net/media/jai/builds/release/1_1_3/INSTALL.html#Windows

    and finally do not forget to import the following as well.

    import com.sun.media.jai.codec.*;
    import javax.media.jai.JAI;
    import javax.media.jai.RenderedOp;
    import javax.media.jai.OpImage;
    import java.awt.image.renderable.ParameterBlock;
    import java.awt.RenderingHints;

    Thanks for everyone again.

  32. George Sun Avatar
    George Sun

    It works like a charm, thanks for the great work!

  33. Alex Avatar
    Alex

    Thanks! Working perfectly well!
    I tried many different code-pieces as well like others…
    Thanks again.
    Alex

  34. Nikhil Avatar
    Nikhil

    I am new to develope a jsp project. please give me detail abt how to use this code…
    plsss

  35. Nikhil Avatar
    Nikhil

    I am using templates in my jsp project and i want apply images of 100pxX100px to every template…. original size of the image may be anything…. please help me out

    1. Devon Avatar

      Nikhil,

      I am sorry but can’t really provide much more than this code. It’s also 7+ years old, so there may be much better ways to do it now, I don’t know.

  36. Nikhil Avatar
    Nikhil

    Although this code is too much old I cant find the way to resize the images in good resolution…

Leave a Reply

Your email address will not be published. Required fields are marked *

PHP Code Snippets Powered By : XYZScripts.com