What is the best way to resize a JPEG and store it in the Filesystem

Hi All,
I have developped a CMS System that renders JPEGs if it does not have the images available within the desired width already. Within my development setup (Dell Latitude D800 with ubuntu dapper drake) everything works fine and fast, as expected. Then I uploaded the application to my V20Z Server with 4gb RAM and the systems performance goes to its knees. I have hooked in a Java Profiler to see where the problem is, and it showed me that it is hanging wthin
sun.java2d.SunGraphics2D.drawImage(Image, int, int, ImageObserver) which I use to draw my Image to a BufferedImage. Below is my complete source code That I am using. Plus the orofiling results
Do not be confused as I am using the Turbine Framework, which gives me a RawScreen which gives me Access to the HttpServletResponse...
package de.ellumination.carmen.modules.screens;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Iterator;
import java.util.Locale;
import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.plugins.jpeg.JPEGImageWriteParam;
import javax.imageio.stream.ImageOutputStream;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.apache.turbine.modules.screens.RawScreen;
import org.apache.turbine.util.RunData;
import de.ellumination.carmen.om.ImagePeer;
public class Image extends RawScreen
public static final float DEFAULT_COMPRESSION_QUALITY = 1.0F;
* Logger for this class
private static final Logger log = Logger.getLogger(Image.class);
@Override
protected String getContentType(RunData data)
return "image/jpeg";
@Override
protected void doOutput(RunData data) throws Exception
int imageId = data.getParameters().getInt("id");
int width = data.getParameters().getInt("width", -1);
int height = data.getParameters().getInt("height", -1);
HttpServletResponse response = data.getResponse();
de.ellumination.carmen.om.Image image = ImagePeer.retrieveByPK(imageId);
File imgFile = new File(image.getLocation());
if(width > 0 || height > 0)
outputScaledImage(imgFile, response, width, height);
else
outputImage(imgFile, response);
private void outputScaledImage(File imageFile, HttpServletResponse response, int width, int height) throws Exception
File scaledFile = new File(imageFile.getParent() + System.getProperty("file.separator") + width + "_" + imageFile.getName());
if(scaledFile.exists())
outputImage(scaledFile, response);
else
scaleImage(imageFile, scaledFile, width);
outputImage(scaledFile, response);
private void outputImage(File imageFile, HttpServletResponse response) throws Exception
FileInputStream in = new FileInputStream(imageFile);
response.setContentLength((int) imageFile.length());
OutputStream out = response.getOutputStream();
int bSize = 10240;
byte[] buffer = new byte[bSize];
int inBuffer = 0;
while (inBuffer >= 0)
inBuffer = in.read(buffer);
if (inBuffer > 0)
out.write(buffer, 0, inBuffer);
* scales the image to its new size. while scaling the Image, the code first resizes the image using the new Width Parameter.
* If the Image is to high after scaling, it then uses the Images height to determin the scaling Factor.
* @param inputFile the original Image
* @param outputFile the File to store the scaled image to
* @param compressionQuality the compression Quality to use
* @param newWidth the desired images width
* @param newHeight the desired images height
public static void scaleImage(File inputFile, File outputFile, float compressionQuality, int newWidth, int newHeight)
try
if (inputFile.exists())
BufferedImage hiRes = ImageIO.read(inputFile);
double scaleFactor = (double) newWidth / (double) hiRes.getWidth(null);
int tempHeight = (int) (hiRes.getHeight(null) * scaleFactor);
if (tempHeight > newHeight)
scaleFactor = (double) newHeight / (double) hiRes.getHeight(null);
int width = (int) (hiRes.getWidth(null) * scaleFactor);
int height = (int) (hiRes.getHeight(null) * scaleFactor);
scaleImage(outputFile, compressionQuality, hiRes, width, height);
catch (IOException e)
log.error("Unable to create the thumbnail " + outputFile.getAbsolutePath() + " from " + inputFile.getAbsolutePath() + " because of the following Reason.", e);
* scales the image to its new size. while scaling the Image, the code first resizes the image using the new Width Parameter.
* If the Image is to high after scaling, it then uses the Images height to determine the scaling Factor. This method uses the
* default compression quality to store image data.
* @param inputFile the original Image
* @param outputFile the File to store the scaled image to
* @param newWidth the desired images width
* @param newHeight the desired images height
public static void scaleImage(File inputFile, File outputFile, int newWidth, int newHeight)
scaleImage(inputFile, outputFile, DEFAULT_COMPRESSION_QUALITY, newWidth, newHeight);
* scales the image to its new size. while scaling the Image, the code first resizes the image using the new Width Parameter.
* uses the highest image compression quality by default.
* @param inputFile the original Image
* @param outputFile the File to store the scaled image to
* @param compressionQuality the compression Quality of the new Image
* @param newWidth the desired images width
public static void scaleImage(File inputFile, File outputFile, float compressionQuality, int newWidth)
try
if (inputFile.exists())
BufferedImage hiRes = ImageIO.read(inputFile);
double scaleFactor = (double) newWidth / (double) hiRes.getWidth(null);
int width = (int) (hiRes.getWidth(null) * scaleFactor);
int height = (int) (hiRes.getHeight(null) * scaleFactor);
// draw original image to thumbnail image object and
// scale it to the new size on-the-fly
scaleImage(outputFile, compressionQuality, hiRes, width, height);
else
log.error("Unable to create the thumbnail " + outputFile.getAbsolutePath() + " from " + inputFile.getAbsolutePath() + " because inputFile not exists: " + inputFile.getName());
catch (IOException e)
log.error("Unable to create the thumbnail " + outputFile.getAbsolutePath() + " from " + inputFile.getAbsolutePath() + " because of the following Reason.", e);
* scales the image to its new size. while scaling the Image, the code first resizes the image using the new Width Parameter.
* uses the highest image compression quality by default.
* @param inputFile the original Image
* @param outputFile the File to store the scaled image to
* @param newWidth the desired images width
public static void scaleImage(File inputFile, File outputFile, int newWidth)
scaleImage(inputFile, outputFile, DEFAULT_COMPRESSION_QUALITY, newWidth);
* This private method actually scales the inputImage to the desired height, width and compression Quality
* @param outputFile The File in which the Image should be stored.
* @param compressionQuality The Compression Quality to be applied to the image
* @param inputImage the original input Image
* @param width the height of the new Image
* @param height the width of the new Image
* @throws IOException
private static void scaleImage(File outputFile, float compressionQuality, BufferedImage inputImage, int width, int height) throws IOException
BufferedImage lowRes = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
java.awt.Image image = inputImage.getScaledInstance(width, height, java.awt.Image.SCALE_SMOOTH);
ImageWriter writer = null;
Iterator iter = ImageIO.getImageWritersByFormatName("jpg");
if (iter.hasNext()) writer = (ImageWriter) iter.next();
File outputPath = outputFile.getParentFile();
if (outputPath != null)
if (!outputPath.exists()) outputPath.mkdirs();
lowRes.getGraphics().drawImage(image, 0, 0, null);
ImageOutputStream ios = ImageIO.createImageOutputStream(outputFile);
writer.setOutput(ios);
ImageWriteParam iwparam = new JPEGImageWriteParam(Locale.getDefault());
iwparam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
iwparam.setCompressionQuality(compressionQuality);
// save thumbnail image to OUTFILE
writer.write(null, new IIOImage(lowRes, null, null), iwparam);
writer.dispose();
ios.close();
image.flush();
inputImage.flush();
lowRes.flush();
* scales the image to its new size. while scaling the Image, the code first resizes the image using the new Width Parameter.
* If the Image is to high after scaling, it then uses the Images height to determin the scaling Factor.
* @param inputImage the original Image
* @param outputFile the File to store the scaled image to
* @param compressionQuality the compression Quality to use
* @param newWidth the desired images width
* @param newHeight the desired images height
public static void scaleImage(BufferedImage inputImage, File outputFile, float compressionQuality, int newWidth, int newHeight)
try
double scaleFactor = (double) newWidth / (double) inputImage.getWidth(null);
int tempHeight = (int) (inputImage.getHeight(null) * scaleFactor);
if (tempHeight > newHeight)
scaleFactor = (double) newHeight / (double) inputImage.getHeight(null);
int width = (int) (inputImage.getWidth(null) * scaleFactor);
int height = (int) (inputImage.getHeight(null) * scaleFactor);
scaleImage(outputFile, compressionQuality, inputImage, width, height);
catch (IOException e)
log.error("Unable to create the thumbnail " + outputFile.getAbsolutePath() + " because of the following Reason.", e);
All Threads     702.570     100 %
java.lang.Thread.run()     551.322     78 %
de.ellumination.carmen.modules.screens.Image.doOutput(RunData)     170.666     24 %
de.ellumination.carmen.modules.screens.Image.outputScaledImage(File, HttpServletResponse, int, int)     170.108     24 %
                         de.ellumination.carmen.modules.screens.Image.scaleImage(File, File, int)     170.108     24 %
                              de.ellumination.carmen.modules.screens.Image.scaleImage(File, File, float, int)     170.108     24 %
                                   de.ellumination.carmen.modules.screens.Image.scaleImage(File, float, BufferedImage, int, int)     165.787     24 %
                                        sun.java2d.SunGraphics2D.drawImage(Image, int, int, ImageObserver)     165.189     24 %
                                        com.sun.imageio.plugins.jpeg.JPEGImageWriter.write(IIOMetadata, IIOImage, ImageWriteParam)     397     0 %
                                        javax.imageio.ImageIO$ImageWriterIterator.next()     69     0 %
                                        javax.imageio.ImageIO.createImageOutputStream(Object)     47     0 %
                                        java.awt.image.BufferedImage.<init>(int, int, int)     36     0 %
                                        java.awt.Image.getScaledInstance(int, int, int)     23     0 %
                                        java.awt.image.BufferedImage.getGraphics()     21     0 %
                                   javax.imageio.ImageIO.read(File)     4.320     1 %
                    de.ellumination.carmen.om.BaseImagePeer.retrieveByPK(int)     557     0 %
               de.ellumination.carmen.modules.screens.Index.doBuildTemplate(RunData, Context)     1.673     0 %
          org.apache.catalina.startup.Bootstrap.main(String[])     151.225     22 %
          org.quartz.core.QuartzSchedulerThread.run()     22     0 %
Now I am looking for the Best way to solve my problem. Maybe I am wrong from the get go.
Runtime Setup Java 1.5.0_04 Tomcat 5.5.12 V20z (AMD64 Opteron 4gb RAM)
Any help is heighly appreciated
Kind regards

This is a bad thing to do with JPEGs. You're better off just reducing the 'q' if you want a smaller/faster/lower resolution image. That way you're throwing away resolution intelligently. Using scaling you're throwing resolution away unintelligently. I was on a project where 40,000 images were scaled when they should have been low-q'd. Don't do it.

Similar Messages

  • What is the best way to resize a clip

    What is the best way to resize a clip? I have some clips in 1280x720p and a B camera shot of the same person that was shot at 1440x1080p and I want to multi-edit them so they need to be the same size. Is there a way inside FCP to re-interpret the 1440x1080 to 1280x720 or do I have to Export them as smaller clips and re-import them? Just have a lot of clips so would be good to find a internal FCP way of doing it.

    Well Zeb, again with the insults. If you had just stated simply "What codec" are you using that would have been fine. But instead you decided to insult me and assume I knew nothing.
    FYI I started working with video in 1985 and was one of the first to use Digital Video in 1991 as a Software Developer. So I can assure you I know a lot about codecs and NLE having even written one once. One of the things I learned in IT was to always ask for the best route through a problem from the experts around you before wasting valuable time and money finding your own, and usually the dead-ends at that!
    So there you go, next time I'll mention the codec and next time if you could be more polite then things will progress more smothely on here

  • What is the best technique to resize a clip and overlay it on a difficult shape, like a broken piece or mirror?

    What is the best technique to resize a clip and overlay it on a difficult shape, like a broken piece or mirror?

    Best would be cutting a matte in Photoshop, or as Mr. Grenadier suggests, using Motion or After Effects - but here is a way to do it staying within FCP - see if this helps:
    http://vimeo.com/34973575
    MtD

  • We have always used one iTunes account and I want to crate a new account for my daughter.  What is the best way to go about this and will she need to download free apps again?

    We have always used one iTunes account and I want to crate a new account for my daughter.  What is the best way to go about this and will she need to download free apps again?

    Not going to happen the way you want it to.
    When you add a gift card balance to the Apple ID, it's available for the Apple ID.
    Probably best to create unique Apple ID's for each... this will also make things easier in the future as purchases are eternally tied to the Apple ID they were purchased with.

  • What is the best way to transfer my music and pictures from my old PC to my new Macbook Pro?

    What is the best way to transfer my music and pictures from my old PC to my new Macbook Pro?

    This may help;
    http://www.apple.com/support/macbasics/migration/
    Ciao.

  • What is the best way to safeguard my files and pictures before I send off my MacBook Pro to get fixed?

    What is the best way to safeguard my files and pictures before I send off my MacBook Pro to get fixed? I am running Mavericks and use an AirPort Time Machine to back-up all my files.

    Back up all data on the internal drive(s) before you hand over your computer to anyone. You need at least two independent backups to be completely safe. There are ways to back up a computer that isn't fully functional—ask if you need guidance.
    If privacy is a concern, erase the data partition(s) with the option to write zeros* (do this only if you know how to restore to an empty drive.) Don’t erase the recovery partition, if present.
    Keeping your confidential data secure during hardware repair
    Apple also recommends that you deauthorize a device in the iTunes Store before having it serviced.
    *An SSD doesn't need to be zeroed.

  • What is the best way of deploying a jsp and bc4j aplication

    Hi
    I would like to know what is the best way of deploying a jsp and
    bc4j aplication in ias 9i.
    thanks in advanced
    rjc

    In the page I simply referenced the facescontext directly... no need for a custom servlet.
    public void createcookie() {
    FacesContext fc = FacesContext.getCurrentInstance();
    HttpServletResponse resp = (HttpServletResponse)fc.getExternalContext().getResponse();
    Cookie userCookie = new Cookie("cookiename", "cookievalue");
    userCookie.setMaxAge(-1);
    userCookie.setMaxAge(3600);
    resp.addCookie(userCookie);
    return null;
    public String readcookie() {
    FacesContext fc = FacesContext.getCurrentInstance();
    ExternalContext ec = fc.getExternalContext();
    Map cookiemap = ec.getRequestCookieMap();
    if (cookiemap != null) {
    Cookie cookie = (Cookie) cookiemap.get("cookievalue");
    return cookievalue;
    For reference I could not get getCookies() method of HttpServletRequest to work.. it would only return JSESSIONID.

  • What is the best way to back up photos and videos to a dvd from iPhoto, not in iPhoto format but just in jpeg format to access on either windows or mac

    what is the best way to back up photos and videos to a dvd from iPhoto, not in iPhoto format but just in jpeg format to access on either windows or mac

    When you export the videos out of iPhoto be sure to select Kind = Original.  Otherwise you'll just get an image file of the first frame of the video.
    OT

  • What is the best way to create E-Flyers and insert to Microsoft Outlook??

    What is the best way to create E-Flyers and insert to Microsoft Outlook??

    http://kb.mailchimp.com/article/how-to-code-html-emails
    Once created, the HTML document cab be placed in the Stationery folder.
    On a PC it's here.
    "C:\Program Files\Common Files\Microsoft Shared\Stationery"

  • What is the best way to reformat a mini and reinstall Mavericks

    What is the best way to reformat a mini and reinstall Mavericks?

    Hi ruthefrombenson!
    This article can help you erase your hard drive and reinstall Mavericks:
    OS X Mavericks: Erase and reinstall OS X
    http://support.apple.com/kb/PH14243
    Thanks for being a part of the Apple Support Communities!
    Regards,
    Braden

  • What is the best way to manage 5 users and 6 devices? We dont all want the same merged contacts, we dont all want the same calendar notes, music, pics etc etc.

    What is the best way to manage 5 users and 6 devices? We dont all want the same merged contacts, we dont all want the same calendar notes, music, pics etc etc.

    As long as it is pointed to iTunes it will be accessible via home sharing on Apple TV.
    http://support.apple.com/kb/HT1751?viewlocale=en_US&locale=en_US
    If these are commercial DVD's we can't comment on any conversion process.

  • What is the best way to captue current date and time?

    I got a field in table to capute current date and time...i am
    using SQL Server.
    field name datatype length
    enter_datetime datetime 8
    What is the best way to get current date and time and insert
    to table?.
    Is this way?.
    <cfset curtime = 'dateformat(#now()#,'mm/dd/yyyy')&"
    "&timeformat(#now()#,'hh:mm:ss')'>
    This way looks like time is not entered correctly.
    or any other better way?.

    > get current date and time and insert to table?
    You can use cfqueryparam
    <cfqueryparam value="#now()#"
    cfsqltype="cf_sql_timestamp">
    Or as was suggested, set the default for your table column to
    getdate(). Then you won't have to insert anything. Sql server will
    do it automatically when a new record is created.

  • What is the best way to back up iPhoto and create disc space

    what is the best way to back up iPhoto and then remove the iphoto folder from the mac book and onto the external apple time capsule

    Two different questions
    the best qway to backup is to use TimeMachine or other automatic backjup program
    However this does not allow you to reduce space since a backup need to be a copy of your existing library and as soond as you changge the library you no longer have a backup and sooner or later the photos will be gone form the bakcujp too
    You need to run the iPhoto library on an external drive or had a complete library on and external drive and a smaller library on yoru internal drive using iPhoto Library Manager - http://www.fatcatsoftware.com/iplm/ -  to move photos between the two libraries
    Moving the iPhoto library is safe and simple - quit iPhoto and drag the iPhoto library intact as a single entity to the external drive - depress the option key and launch iPhoto using the "select library" option to point to the new location on the external drive - fully test it and then trash the old library on the internal drive (test one more time prior to emptying the trash)
    And be sure that the External drive is formatted Mac OS extended (journaled) (iPhoto does not work with drives with other formats) and that it is always available prior to launching iPhoto
    And backup soon and often - having your iPhoto library on an external drive is not a backup and if you are using Time Machine you need to check and be sure that TM is backing up your external drive
    LN

  • What's he best way to include Adobe PDFs on my blog?

    What's he best way to include Adobe PDFs on my blog?
    I create worksheets as a teacher and would like to share them from my blog. Currently I am linking to Scribd etc to share PDFs. If I upload the worksheets as an image is there a way to adjust the size/resolution of the PDF for easier viewing? 
    Thanks!

    PDFs are just files. Can you upload files to your blog space? If yes, just upload the PDFs then, in a blog entry, provide the web link (URL) for each file (PDF).
    Or, place the PDFs into your free acrobat.com "files" storage (5GB free). You have one as you have an Adobe ID (needed to make your post here eh).
    https://cloud.acrobat.com/
    You can have acrobat.com provide a "share" link to the PDF. Place that into a blog entry.
    Or - same idea as above (use a "file share" service) -- Microsoft's OneDrive, Adobe's Creative Cloud, Google drive, DropBox, others ...
    Be well...

  • What is a best way to write SQL ?

    Sample Case
    drop table t;
    drop table b;
    create table t ( a varchar2(4), b number, c varchar2(1));
    insert into t values ('A00', 10, 'R');
    insert into t values ('A01', 11, 'R');
    insert into t values ('A02', 12, 'R');
    insert into t values ('A03', 13, 'R');
    insert into t values ('A00', 10, 'P');
    insert into t values ('A01', 11, 'P');
    insert into t values ('A02', 12, 'P');
    insert into t values ('A03', 13, 'P');
    commit;
    create table b ( j varchar(4), k varchar2(1), l varchar2(5), m number(3), n varchar2(5), o number(3));
    insert into b values ('A00', 'P', 'FIXED', 100, 'FLOAT', 60);
    insert into b values ('A01', 'P', 'FIXED', 101, 'FIXED', 30);
    insert into b values ('A02', 'R', 'FLOAT', 45, 'FLOAT', 72);
    insert into b values ('A03', 'R', 'FIXED', 55, 'FLOAT', 53);
    commit;
    10:19:13 SQL> select * from t;
    A B C
    A00 10 R
    A01 11 R
    A02 12 R
    A03 13 R
    A00 10 P
    A01 11 P
    A02 12 P
    A03 13 P
    8 rows selected.
    10:19:19 SQL> select * from b;
    J K L M N O
    A00 P FIXED 100 FLOAT 60
    A01 P FIXED 101 FIXED 30
    A02 R FLOAT 45 FLOAT 72
    A03 R FIXED 55 FLOAT 53
    1/     In table t each reference having 2 records one with P another is with R
    2/     In table b each refrence merged into single record and there are many records which are not existing in table t
    3/      both t and j tables can be joined using a = j
    4/     If from table t for a reference indicator is 'P' then if have to pick up l and m columns, if it is 'R' then I have to pick up n and o columns
    5/     I want output in following format
    A00     P     FIXED          100
    A00     R     FLOAT          60
    A01     P     FIXED          101
    A01     R     FIXED          30
    A02     P     FLOAT          72
    A02     R     FLOAT          45
    A03     P     FLOAT          53
    A03     R     FIXED          55
    6/     Above example is a sample ouput, In above example I have picked up only l,m,n,o columns, but in real example there are many columns ( around 40 ) to be selected. ( using "case when" may not be practical )
    Kindly suggest me what is a best way to write SQL ?
    thanks & regards
    pjp

    Is this?
    select b.j,t.c as k,decode(t.c,'P',l,n) as l,decode(t.c,'P',m,o) as m
    from t,b
    where t.a=b.j
    order by j,k
    J K L M
    A00 P FIXED 100
    A00 R FLOAT 60
    A01 P FIXED 101
    A01 R FIXED 30
    A02 P FLOAT 45
    A02 R FLOAT 72
    A03 P FIXED 55
    A03 R FLOAT 53
    8 rows selected.
    or is this?
    select b.j,t.c as k,decode(t.c,b.k,l,n) as l,decode(t.c,b.k,m,o) as m
    from t,b
    where t.a=b.j
    order by j,k
    J K L M
    A00 P FIXED 100
    A00 R FLOAT 60
    A01 P FIXED 101
    A01 R FIXED 30
    A02 P FLOAT 72
    A02 R FLOAT 45
    A03 P FLOAT 53
    A03 R FIXED 55
    8 rows selected.

Maybe you are looking for

  • Can't Install Boot Camp Software on WinXp SP2

    Here's what I have done thus far: 1. Partition HD such that windows has its own 30 gig partition. 2. Install FAT32 Windows XP SP2 on the new 30 gig partition. 3. Insert MacOSX disk that came with my brand new Mac Mini as to install Boot Camp and driv

  • Argh! Message bundle file names are not allowed to have dots???

    It took me several hours to find the reason for this exception: java.util.MissingResourceException: Can't find bundle for base name properties\com.domain.prj.huj.MainApp.Messages, locale de_DE      at java.util.ResourceBundle.throwMissingResourceExce

  • 2 Factor Authentication for Anyconnect VPN using ISE

    We are planning to implement dual factor authentication for Anyconnect VPN. The end users will be authenticated using domain name in machine certificates and username password with ISE used as radius server. We have the following approaches to achiev

  • Force list view?

    Is it possible to force, or default, list view? Like when II open a new finder window, it is always opening in icon display mode. I'm sure there's a way to tell it to always show items in list mode, but maybe not?

  • Setting default font size in Safari

    Hi. I like to set my font size in Safari to one level below the default. I usually do this everytime I open up a Safari window and hit Command+Minus or go to View > make text smaller. Anyway, I was wondering if there was a way I could set this to def