Resize JPEG and GIF'S Images - JSP

Java greetings!
Somebody knows as can make to create an image pequena(sendo the miniature), without losing quality?
therefore I am making upload of images, that are recorded in the DB... are wanting to make in the following way: thus q the user to make upload of the image, is created a miniature of the image and kept original(having been image GREAT).
Somebody can help me? or to indicate some classroom and examples so that it can make this?
Since already I am thankful!

how I make to use the thumbnail Classroom with my Servlet, therefore the thumbnail classroom uses parameters of String and the binary Servlet. as to decide this?
Since already I am thankful!
package com.brutus;
import java.io.*;
import java.util.*;
import java.sql.*;
import javax.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class BlobUploadServlet extends HttpServlet{
private static String dbUserName = "root";
private static String dbPassword = "";
private static String urlDb = "jdbc:mysql://localhost/test";
private static final char CR = 13;
private static final char LF = 10;
protected String boundary = null;
protected Hashtable params = new Hashtable();
public void doPost( HttpServletRequest request,HttpServletResponse response )
throws ServletException, IOException{
ServletOutputStream out = response.getOutputStream();
ServletInputStream in = request.getInputStream();
BufferedInputStream bin = new BufferedInputStream(in);
boundary = getBoundary(request.getHeader("content-type"));
out.println("<html><body><pre>");
out.println("boundary =\n"+boundary);
out.println();
byte[] bytes = new byte[128];
in.readLine(bytes,0,bytes.length);
String line = new String(bytes);
Hashtable header = null;
while(in.readLine(bytes,0,bytes.length)>=0){
line = new String(bytes);
if(line.startsWith("Content-Disposition:")){
out.println(line);
header = parseHeader(line);
updateParams(header);
}else if(line.startsWith("Content-Type:")){
params.put("Content-Type",
line.substring("Content-Type:".length()).trim());
}else{
if(header!=null&&bytes[0]==13){
if(header.containsKey("filename")){
displayParams(out);
out.println(" ...saving payload");
savePayload(params,bin);
header = null;
}else{
String name = (String)header.get("name");
String value = getParameter(in).trim();
params.put(name,value);
}if(line.indexOf(boundary)>=0)
out.println(line);
bytes = new byte[128];
out.println("</pre></body></html>");
out.close();
private void displayParams(ServletOutputStream out)
throws java.io.IOException{
for (Enumeration e = params.keys();e.hasMoreElements();) {
String key = (String)e.nextElement();
out.println(" "+key+" = "+params.get(key));
private void updateParams(Hashtable header){
for (Enumeration e = header.keys();e.hasMoreElements();) {
String key = (String)e.nextElement();
params.put(key,header.get(key));
private String getParameter(ServletInputStream in)
throws java.io.IOException{
byte[] bytes = new byte[128];
in.readLine(bytes,0,bytes.length);
return new String(bytes);
private String getBoundary(String contentType){
int bStart = contentType.indexOf("boundary=")+"boundary=".length();
return "" + CR + LF + "--" + contentType.substring(bStart);
private void savePayload(Hashtable params,BufferedInputStream is)
throws java.io.IOException{
int c;
PushbackInputStream input = new PushbackInputStream(is,128);
ByteArrayOutputStream out = new ByteArrayOutputStream();
while ( (c=read(input,boundary)) >= 0 )out.write( c );
//int id = Integer.parseInt((String)params.get("ID"));
saveBlob((String)params.get("filename"),out.toByteArray());
out.close();
private int read( PushbackInputStream input, String boundary )
throws IOException
StringBuffer buffer = new StringBuffer();
int index = -1;
int c;
do {
c = input.read();
buffer.append( (char)c );
index++;
while ( (buffer.length() < boundary.length()) && (c == boundary.charAt(index)) );
if ( c == boundary.charAt(index) ){
int type = -1;
if ( input.read() == '-' )
type = -2;
while ( input.read() != LF );
return type;
while ( index >= 0 ){
input.unread( buffer.charAt(index));
index--;
return input.read();
private Hashtable parseHeader(String line){
Hashtable header = new Hashtable();
String token = null;
StringTokenizer st = new StringTokenizer(line,";");
while(st.hasMoreTokens()){
token = ((String)st.nextToken()).trim();
String key = "";
String val = "";
int eq = token.indexOf("=");
if(eq <0) eq = token.indexOf(":");
if(eq >0){
key = token.substring(0,eq).trim();
val = token.substring(eq+1);
val = val.replace('"',' ');
val = val.trim();
header.put(key,val);
return header;
public void saveBlob(String description,byte[] out){
String cmd = "INSERT INTO Photos (Description,Image) VALUES(?,?)";
System.out.println(cmd);
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(urlDb,dbUserName,dbPassword);
PreparedStatement pstmt = con.prepareStatement(cmd);
pstmt.setString(1, description);
pstmt.setBytes(2, out);
System.out.println(pstmt.executeUpdate());
con.close();
catch(ClassNotFoundException e){
e.printStackTrace();
catch(SQLException e){
e.printStackTrace();
}

Similar Messages

  • Jpeg and gif images are not fuzzy

    How can I import jpeg and gif files so that they are crisp and not fuzzy?  I have Lifecycle Designer 7.0
    T

    Look at the bottom of this page as well [http://carlback.blogspot.com/2007/12/apex-and-3rd-party-js-libraries.html]
    Patrick Wolf
    Carl,
    the only drawback with #WORKSPACE_IMAGES# and #APP_IMAGES# is that it doesn't get cached by the browser. So each page request will transmit the hole file again. A caching option for the "Static Files" in the Shared Components would be nice :-)
    About lazy loading with the #WORKSPACE_IMAGES#. I could think about a mod_rewrite rule which translates the additional file request of the JS library into a valid request for APEX.
    Carl Backstrom
    In 3.1 we emit a last modified header now for uploaded files so that should help with browser caching.
    I wonder if anything's changed since then.
    Kofi

  • Why won't jpegs and gifs open

    Can anyone tell me why jpegs and gifs that are in a document created in Word for Windows won't open in Word for Mac. This is a huge problem for me because I have webpages that I created in Word for Windows and when I edit them in Word for Mac I loose the graphics.

    Word for Windows is a really poor webpage editor. It assumes everyone in the world uses Internet Explorer, and does not take the precautions of following standard HTML coding. A webpage document created in word may work in only Internet Explorer and maybe a few other web browsers.
    My suggestion is to learn HTML and/or use a webpage editor known to follow w3.org standards to the letter like http://www.barebones.com/ BBEdit. You can try several other web browsers for the Mac as well:
    http://www.macmaps.com/browser.html
    Disclaimer: Reference to links I make to my Macmaps.com website are a for your information only type reference. I do not get any profit from this page, and it is open to the public.

  • Putting jpegs and gifs into an applet???  - new programmer

    I am a new programmer trying to learn how to put jpegs and gifs into my applet. I am using a paint method to draw pictures. Is there a way that I can insert jpegs and gifs into this at certain x and y coordinates?
    Thanks.

    http://java.sun.com/docs/books/tutorial/uiswing/painting/usingImages.html

  • Lightroom 5.6 Export RAW to Resized JPEG Producing Poor Quality Images

    I have the latest Lightroom 5.6 and am running into a problem that I never had EVER and I've been using the same workflow since LR1. I shoot in RAW and want to send my client JPEG proofs (resized to 1000px, 100% quality, and 96dpi, sRGB). I use the export feature and have tried everything, even saving the resized image at 300dpi but the export results are still absolutely horrible. The photo is muddled and blurry no matter what I try. This is obviously not a color space issue, or monitor/browser issue and as I said before, I've done resizing through LR plenty of times without this much compression loss. Anyone else running into this? What's the solution?
    I took the same RAW file and exported to JPEG with resizing checked off and the image looked sharp as a tack like my RAW file in LR.
    So, there is obviously something wrong with LR RAW to JPEG export when resizing. Which has NEVER been an issue before.
    Adobe, seriously, get your S%&T together!

    Never seen anything like that before. I export with resizing all the time. As long as the quality is somewhat up from 80% (100% is complete overkill) and I do appropriate output sharpening, the quality is always superb. Of course there is only so much you can do with a 1000 pixels so don't expect to zoom endlessly in on that. The ppi does not matter at all when you specify a size in pixels. Can you post an example?

  • Photoshop CS6 Saving JPEGs as GIF's???

    I am doubble clicking my .jpg images from Bridge CS6 into Photoshop CS6 to downsize the image and after i change the image to move across to a forum elsewhere.
    The Save As" option gives me all the normal file. options, i click the drop down bar and select JPEG, and then automatically the .jpg image above turns into a .gif file???
    I have closed out and tried resaving on several different images of mine and keep getting this .gif once selecting the JPEG, and- .gif setting if i select ok to go forward with the.gif.
    I want to save as a simple
    JPEG with a size 8 for web forum purpose.
    Whats with this?
    Please help with this, is it a bug??
    Thanks
    Here is the screen pic.-->
    Sorry about the blurryness if you click the image it wil enlarge. Cheers
    OSX
    10.6.8
    CS5 Master Collection Suite Owner &
    Lightroom 4.
    ******UPDATE- Going through all different file formats, saved everything as something different.
    Saving my image as .Photoshop Raw- Saved my Photo as a JPEG then i got to choose size 8 - ok. Done.
    Definatley a BUG!!***** in file saving!!!******

    To be perfectly clear, you CAN use the Extra Plug-ins Folder specification to point to a separate folder you've created where you have put ONLY your 3rd party plug-ins.  It can be a neat way to help organize plug-ins, especially if you don't prefer to copy things into your Photoshop installation area.
    Just don't point it anywhere in the installation area for another version of Photoshop.
    The basic problem is that many folks, in trying to save time, choose to point their Extra Plug-ins Folder setting to the plug-ins subfolder inside their old Photoshop installation area, thinking that will just make them all available to the new version.  The key thing is that the old versions of Photoshop ALSO had put their own Adobe-supplied plug-ins there.  The conflict arises when the new version of Photoshop starts and tries to enumerate the plug-ins, including those found in the Extra Plug-ins Folder, it finds overlap between its own plug-ins and the old ones it finds there.
    -Noel

  • 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

  • Can no longer copy and past jpg and gifs into InDesign from c:\user\doc\pics

    Here is the error message we get when doing a copy and past from the hard drive to InDesign.
    Error Message from InDesign:
    Adobe InDesign may not support the file format, a plug-in that supports the file format may be missing...
    First, do I need to add a plug-in to be able to copy and past jpgs and gifs?
    Second, we have always used clip organizer with no problem. Ability to copy and paste jpg & gif suddenly stopped. We get a box but no image ont the page. Have already tried dumping temp internet files through internet explorer. Have already un & re installed InDesign and repaired and fixed everything I could think of.
    Third, we can use the place command to place jpgs but can not place gifs.
    William (Helping Mrs. White)

    It sounds as if Mrs White needs to search visually for graphics and then place them. She can either set Windows Explorer
    to thumbnail view and drag a graphic on to an InDesign page - this will in effect be placing the graphic, not copying
    and pasting, and is the right way to go. Or she can use File > Place, and set the view in the Explorer window that she
    selects from in the Place command to a thumbnail view to see the graphics.
    GIFs can be placed. They are not a recommended format, but if you are placing clip art then you may have no option.
    So, in answer to your original question, no, you don't need a plug-in to place JPEGs and GIFs. But note that is place,
    not copy and paste.
    k

  • IPhoto won't import jpeg or gif, or any common photo types, from backup CD

    I recently had my hard drive replaced. I had backed up all of my photos on a CD, but iPhoto gives an error message when I try to import some of the jpegs and gifs to the new HD: "The following files could not be imported (they may be an unrecognized file type or the files may not contain valid data". Is this a software issue?

    Back up your iPhoto library, Depress and hold the option (alt) and command keys and launch iPhoto - rebuild your iPhoto library - start at the first option and try each one in order
    LN

  • Changing JPG to JPEG or GIF & resizing

    I'm trying to post my pictures on a website, but the're in JPG and the website only allows JPEG or GIF. How can I change the images, and how can I make them smaller, i've tried making them smaller to export, but they still end up big, so I need another option rather than exporting. Please help.

    Christina:
    Welcome to the Apple Discussions. To resize for other applications just select those you want to resize and use the File->Export->File Export route. There you will have the option to select the size you'd like.
    As for the JPG vs JPEG, have you tried submitting a JPG file? Those two extensions are the same and can be used interchangeably. The JPEG is the more formal representation of that format. If the simple JPG extension is rejected you can use R-Name to batch change the extension to JPEG before you submit them to the site. You'll have to do that after you export from iPhoto.
    OT

  • How to decoding and encoding PNG and GIF images?

    I could decode and encode JPEG images using following create functions which are in com.sun.image.codec.jpeg package.
    JPEGImageDecoder decoder = JPEGCodec          .createJPEGDecoder(inputStream);
    JPEGImageEncoder encoder = JPEGCodec                    .createJPEGEncoder(outputStream);
    But I dont know required package and functions to decode and encode PNG and GIF images. Please help me.

    Is the API that hard to follow?
    ImageIO.read( file/stream/url)
    ImageIO.write( image, format (e.g. PNG, GIF(1), JPEG), file/stream what have you)
    1) Not sure if Java supports GIF saving, it might if you install JAI, or Java 6.

  • Is there a way to save an image file as a jpeg and add -web or -print to the file name?

    I am trying to find a way to save my image file as a jpeg and add -web or -print to the existing file name.  This way I can easily see which files are lower resolution for web posting or high resolution for printing.

    Jason,
    I helped somebody do a very similar thing about a week ago.
    The trick is to use the Batch command's ability to construct a file name.
    Tell the batch to append, e.g. "-x" without quotes, to the name of each saved file.
    The batch runs an Action which does a save as JPEG, resize image, add logo, save as JPEG, then close document.
    The output is "<document name>-x.jpg" and "<document name>-x-x.jpeg".
    Then use Windows Explorer to rename "*-x-x.jpg" to "*-print.jpg".
    Then rename "*-x.jpg" to "*-web.jpg".
    See http://forums.adobe.com/thread/1038992?start=32
    The name construction that I used there was just an "x" appended to the document name. Use whatever you like. Also juliew subsequently referred to the method as a "double-batch" run, although it is not. One run of the batch will output two JPEGs for each input document.
    I hope the disagreements in that thread don't cause too much disruption.
    If you want, the Batch command itself can be recorded in another Action which would store the parameters of the batch, then you could run that Action anytime without having to set up the details of the batch each time. It would always output to one specific folder, though.

  • Can I resize photos and reduce JPEG file sizes by using Photpshop Elements?

    Can I resize photos and reduce JPEG file sizes by using Photpshop Elements?

    Go to Image>Resize>image size.
    For purpose of web posting, go to File>save for web.

  • 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();
    .

  • Resizing JPEG Files and overwrite existing files

    I've got a folder with about 30 subfolders with JPEGs only. I need to resize all of them to a specific size and they must stay within the subfolder structure they currently reside in. I have selected all of the files (using the show files in subfolders menu setting) and have tried to Export so that the smaller files go back in the original folder and also "Overwrite WITHOUT WARNING". When I do this, LR3 will go through it's process, but will come up with a message like this one:
    Is what I am seeking to accomplish not possible in Lightroom? Or is there another way to do this? I'm about ready to make a Photoshop Action to get this over with but wanted to see if LR can do what I need it to do.

    Thanks for the response. These are not original RAW images, but are images for a project I'm working on. I have all the original RAW files, but they are scattered throughout my library on different volumes. I had originally exported the RAWs into one JPEG folder, then sorted images into a bunch of different subfolders during the editing process. Some files still have camera names and some are renamed, so doing it over again by re-exporting and sorting to move in chunks is not an option. I simply want a way to overwrite the images without having to resort everything back into the different subfolders. Isn't that what the "Overwrite WITHOUT WARNING" should be for? I don't understand why it won't let me overwrite the images.

Maybe you are looking for

  • Set default transaction in Ic webclient

    Hi All, I am working in IC WEBCLIENT. When I am launching the transaction crm_ic and going to interaction history in navigation bar and in show field I am choosing Business Activity I am getting the mails and while choosing that mail I am getting Com

  • Preflight warnings for registration color -- how to avoid?

    In preflighting, is there any way to turn off registration color and font color warnings when checking for spot colors and non-CMYK colors? I spend a lot of time tunneling through lists of fonts (that use non-CMYK color in their definitions) and regi

  • Calendar app corrupted, how to download new one

    My Yosemite calendar app won't open. Error message indicates it is corrupted. How do I download new calendar aoo?

  • CRM2007 Factsheet - updating custom fields at the same time

    I need to change our Factsheet in CRM2007. So far, I've managed to get a new view on the Factsheet and have managed to hard-code some data into it from the Get_* method for the field in the CN** class. However, my requirement is to grab some data fro

  • Posting on 13 posting period

    Hi experts, i just closed posting period for the period 2011(jan - dec) but my posting periods 13 to 16 is open, still some invoices are pending i need to enter MIRO transactions on 13 posting period, how it can manage ? regards, Sanju M S