How to scale an image(URGENT)

I am having a problem in scaling an image.
The code I've written is as follows.
Toolkit tk=Toolkit.getDefaultToolkit();
Image img=tk.getImage("abc.png");
img=getScaledInstance(100,100,Image.SCALE_FAST);
Then when I draw the image, it doesn't scale it. It draws nothing. But if i remove the line, getScaled...,
then it is loaded properly.
Wat can be the problem?
Also, if any1 can tell other ways to scale an image to a predefined size, please tell me.
Its very URGENT, please respond fast.

import java.awt.*;
import java.awt.geom.*;
import java.awt.image.*;
import java.io.*;
import java.net.*;
import javax.imageio.*;
import javax.swing.*;
public class X {
    public static BufferedImage readScaled(URL url, int w, int h) throws IOException {
        BufferedImage orig = ImageIO.read(url);
        int transparent = orig.getColorModel().getTransparency();
        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
        GraphicsDevice gd = ge.getDefaultScreenDevice();
        GraphicsConfiguration gc = gd.getDefaultConfiguration();
        BufferedImage image = gc.createCompatibleImage(w, h, transparent);
        Graphics2D g = image.createGraphics();
        g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
        double scaleX = w / (double) orig.getWidth();
        double scaleY = h / (double) orig.getHeight();
        AffineTransform xform = AffineTransform.getScaleInstance(scaleX, scaleY);
        g.drawRenderedImage(orig, xform);
        g.dispose();
        orig.flush();
        return image;
    public static void main(String[] args) throws IOException {
        String url = "http://i.a.cnn.net/cnn/interactive/world/0312/gallery.saddam.captured/1.saddam.beard.jpg";
        BufferedImage image = readScaled(new URL(url), 400, 400);
        JLabel label = new JLabel(new ImageIcon(image));
        JFrame f = new JFrame("X");
        f.getContentPane().add(label);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
}

Similar Messages

  • Can anyone explain me how to scale the image in canvas in flash builder 4.6

    Can anyone explain me how to scale the image in canvas in flash builder 4.6, Scaling of image in component , can i get some examples ..  it should set almost all size screen

  • How to scale linked images back to 1:1 {normal proportions}?

    Hi there,
    I am workind on document, containing 470 linked images. I accidentaly did some operation with frame fitting probably, so all my images got non-proportional scaling now. Amount of Undos was not long enough...
    Do you have some clever recipe how to scale them back to normal aspect ratio?

    Well,
    thank you for your reply, but I do not uderstand your advice clearly: If the chain link is not broken, I just resize the frame containing photo and keep that bad proportions which I want to get rid of.
    OK, I can just click the Content Grabber circle button and resize the image manualy to be about fine. But in case of 470 links I hoped in some one-click-magic... {"Equalize the proportions of linked images" button to be exact }
    Thank you...

  • How to scale an image displayed on JButton

    Hi all,
    I has a panel contains 42 buttons of the same size arranged with GridLayout manager. I try to display some images on the buttons. But the problem is that the image bigger than buttons. Is it possible to scale the image to fit the size of button and which method is used?
    Thank you very much in advance.

    Hi,
    I try your tips. But I still see no changes.
    here is the code. I wonder where I go wrong.
                    Image i=Toolkit.getDefaultToolkit().getImage("red.JPEG");                    i.getScaledInstance(-5,5,Image.SCALE_DEFAULT);
                    //or i.getScaledInstance(10,1,Image.SCALE_DEFAULT);                          
         ImageIcon ic=new ImageIcon(i);
                   button1.setIcon(ic);//add image to the button
        

  • How to scale an Image?

    I found lots of threads about scaling images but none worked for me. The closest one's are these:
    image.getScaledInstance(width, height, Image.SCALE_DEFAULT);seems to scale the image but the resulting image returns "-1" for both getWidth()/getHeight().
    The other "solution" sets the correct dimension nut the resulting image is just black (= background color):
    BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    Graphics2D biContext = bi.createGraphics();
    biContext.drawImage(image, 0, 0, width, height, null);           
    result = bi;

    It looks like you need to make sure that your original image
    is fully loaded prior to rendering.
    You should use java.awt.MediaTracker for that.
    Or load your image with javax.imageio.ImageIO.read() method.
    Dmitri

  • How to scale an image? iOS 7.1........

    Updated to iOS 7.1 but still can't set a wallpaper to the dimension I want.
    Am I doing something wrong?

    Why your wallpapers look messed up on iOS 7, and how to fix them!
    http://www.imore.com/having-issues-wallpapers-ios-7-heres-why-and-how-fix-it
    How to Change iPad Wallpaper and Grab or Save Images from the Web
    http://portables.about.com/od/newsandviews/ss/iPad-tutorials_5.htm
    You could use the free Instafit app https://itunes.apple.com/us/app/instafit-post-photos-to-instagram/id591706840?mt =8
     Cheers, Tom

  • How to scale image to A3 size in adobe reader XI

    Hi there,
    Im having trouble trying to find out how to scale an image to fit onto an A3 sixe paper. I tried the fit command but it doesnt 'fit' the image to A3 size. Any help would be appreciated.
    Tamika

    As far as I know, this cannot be done with the free Reader.

  • How do I re-scale cropped images in Fianal Cut Express 4?

    How do I re-scale cropped images to the correct aspect ratio in the sequence? I am in Final Cut Express 4. The manual says: 'Modify>Scale to sequence' but I do not see this command in the Modify drop-down menu. Does anyone know where this is located or how to to re-scale? Many thanks for any help.

    I'm not quite sure exactly what the problem is and I am no expert.
    However, if the photos are too small you can simply enlarge them to fit  the frame.
    To do this, select the clip in the timeline and open the Motion tab in the Viewer.
    Drag the Scale slider along until the photo enlarges the correct amount. (If the picture does not enlarge, double click the clip)
    If you have lots of photos which need exactly the same enlargement you can copy (Cmd C) the treated picture and then select all the others.
    Go up to the Edit menu and select "Paste Attributes".
    A window will open. Tick the "Basic Motion" box and all the selected pictures will be enlarged.
    They will then need rendering.

  • Urgent : how to put an image into database and how to get it from it?

    hi,
    in the database i made a longblob type for image, and in my java code i have the path of the image (String): "C:\............." and i want to put this image in my data base.
    also i want to know how to get the image after put it in the database.
    please help me, it's so urgent.

    This is a way of getting the image out of the database.
    class yourClass{
    private byte[] buff;
    private ByteArrayOutputStream byteArrayOutputStream;
    public yourClass()
    Statement statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
    ResultSet result = statement.executeQuery("your query");
    while ( result.next()){
    try{
    BufferedInputStream bin = new BufferedInputStream(rs.getBinaryStream("imagecolumn"));
    byteArrayOutputStream = new ByteArrayOutputStream();
    int length = bin.available();
    buff = new byte[length];
    while ( bin.read( buff, 0, length ) != -1 ) {
    byteArrayOutputStream.write( buff, 0, length );
    bin.close();
    catch(Exception e){
    The class about is used to take the image out of the database and store it in an object which is then streamed out through a servlet to display on the jsp page.
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.io.*;
    import java.util.*;
    import java.sql.*;
    public class ImageServlet extends HttpServlet {
    public void init() throws ServletException {    }
    public void destroy() {    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
    try
    yourClass pro = (yourClass)request.getSession().getAttribute("object");
    while ( iterator.hasNext() ) {
    pro = ( Product ) iterator.next();
    response.setContentType("image/jpg");
    ByteArrayOutputStream byteArrayOutputStream = pro.getImage();
    response.setContentLength( byteArrayOutputStream.size() );
    response.getOutputStream().write( byteArrayOutputStream.toByteArray() );
    response.getOutputStream().flush();
    return;
    catch (Exception e)
    e.printStackTrace();
    throw new ServletException(e);
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
    doGet(request, response);
    This is a little messy but if you search the forums you will find out more on it. Search for Images and database.

  • How to scale image, and not scale corner radius

    Working on a catalog with image in a .075" corner radius shape. The page are generated by a CMS system so the images are needing to be recropped and scaled. Cannot find a way to scale the image and keeping the rounded corner radius at .075".
    CS5 Mac

    Thanks for your reply and desire to help. I realize that but found that you can only adjust width or height and not even scale to get this to work,and other problems with this method.
    I am only interested in being able to scale both frame and image simulataneously and holding the corner shape.
    For a program called InDesign, the lack of this essential basic feature is NOT DESIGN friendly. Anyone designing a catalog would be wise to avoid using anything else but square corners on images.

  • How can I scale an image without it becoming blurry?

    I'm following this tutorial on youtube and I'm doing everything he says, but when I scale the image it becomes blurry on mine and his was still perfect.

    Rick is correct, but there are some features that can give better results than the default scaling:
    http://helpx.adobe.com/after-effects/using/detail-preserving-upscale-effect.html
    http://blogs.adobe.com/aftereffects/2013/06/bicubic-resampling-for-improved-scaling-and-ot her-transformations-in-after-effects.html
    By the way, it helps if you give a lot more information when asking a question. We have no idea what you've tried so far, and we don't even know what version of After Effects you're using.

  • How to create an gray scale png image from intensitie​s values

    Hi,
      I would like create a gray scale png image from set of intensities values which is saved in excel sheet . Is IMAQ tool necessary for this vi?
    thanks & regards
    Manoj

    You posted in the feedback forum, which is not correct for your question. I am guessing you are talking about LabVIEW since you mention "vi".
    manojkp89 wrote:
    Is IMAQ tool necessary for this vi?
    The answer is NO. Plain LabVIEW is sufficient.
    LabVIEW Champion . Do more with less code and in less time .

  • How can I display images in drop down.

    Hi All,
    How can I display images in drop down.
    <select><option>image here</option></select>
    please reply soon.
    anser please
    Thanks

    I have not found html forum..That's just incredible.
    where can i find it ?Sorry, I'm still recovering from that remark.
    please reply soonEvery time you end a post with this, or "urgent" or other such keywords, the forum automatically introduces a 5 minute delay so that will actually make the whole process slower (not faster).

  • How to have multiple images on the same screen? like in the movies where you see several actions at

    how to have multiple images on the same screen? like in the movies where you see several actions at the same time ....
    i don't find  a tutorial in adobe tv....
    thanks !!

    The short answer is that you'll put the source clip(s) for each inset on a different video track, all stacked up. Then use the Scale and Position effects (under "Motion" on the Effect Controls panel) to reduce their size and place them where you want.
    If the content of an inset will involve edited content (where you're cutting among various clips or just trimming out unwanted content from a single clip), then you'll probably find it easier to do all those edits in one sequence, then nest that sequence in the master sequence, where you apply the Scale and Positioning effects. That will save the step of applying the scale and position effects to each edited track item.

  • How to add an image file to Oracle db?

    Need help urgently....Anybody knows how to add an image file (example: jpg)into one of the fields in Oracle database??

    This will do the job..
    package forum;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.io.*;
    import java.util.*;
    import java.sql.*;
    import oracle.jdbc.driver.*;
    //import oracle.sql.*;
    Wanneer een request.getInputStream wordt geconferteerd naar een "String" (zie later) dan ziet de output in tekstformaat er als volgt uit:
    -----------------------------7d280152604f4 Content-Disposition: form-data; name="oploadfile"; filename="C:\WINNT\Profiles\mvo\Desktop\boodschap.txt" Content-Type: text/plain Deze boodschap dient te worden ge-insert in de database. -----------------------------7d280152604f4 Content-Disposition: form-data; name="StadID" 1234 -----------------------------7d280152604f4 Content-Disposition: form-data; name="SuccessPage" /forum/error.jsp -----------------------------7d280152604f4--
    of opgesplitst
    contentType........... multipart/form-data; boundary=---------------------------7d235ade00f0
    filename.............. "C:\Documents and Settings\Administrator\Desktop\boodschap.txt"
    MIME type............. text/plain
    Wat in database moet.. Dit is de eigenlijke boodschap die moet worden ge-insert in de database.
    Eind boundary......... -----------------------------7d235ade00f0 Content-Disposition: form-data; name="file1"; filename="" Content-Type: application/octet-stream -----------------------------7d235ade00f0--
    We gaan achtereenvolgens:
    1. Kijken of het van het "multipart/form-data" type is (uploaden) en strippen van eerste boundery.
    1.a Geen "multipart/form-data" ? dan... error message
    1.b Groter dan MAX_SIZE ?..dan .. error message
    2. Filenaam van de te uploaden file uitlezen
    3. Mimetype bepalen en bepalen in welke positie van de string het Mimetype ophoudt, cq waar te uploaden file begint
    4. Bepalen waar eind boundery begint
    5. De eigenlijke file uitlezen
    6. Terug converteren naar bytes
    public class WriteBlob extends HttpServlet {
    public static final int MAX_SIZE = ParameterSettings.imageUpload;
    String successMessage = "";
    public void init(ServletConfig config) throws ServletException {
    super.init(config);
    * Process the HTTP Get request
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    DataInputStream in = null;
    FileOutputStream fileOut= null;
    PrintWriter out = response.getWriter();
    int kb_size = 0;
    boolean pass2 = true;
    String message = "";
    String responseRedirect = "/forum/uploaden.jsp?message="+" Uploaden geslaagd";
    try
    //get content type of client request
    String contentType = request.getContentType();
    // Start stap 1...content type is multipart/form-data
    if(contentType != null && contentType.indexOf("multipart/form-data") != -1)
    //open input stream
    in = new DataInputStream(request.getInputStream());
    //get length of content data
    int formDataLength = request.getContentLength(); // totale lengte van de inputstream
    //initieer een byte array om content data op te slaan
    byte dataBytes[] = new byte[formDataLength];
    //read file into byte array
    int bytesRead = 0;
    int totalBytesRead = 0;
    int sizeCheck = 0;
    while (totalBytesRead < formDataLength)
    //kijken of de file niet te groot is
    sizeCheck = totalBytesRead + in.available();
    if (sizeCheck > MAX_SIZE)
    pass2 = false;
    message = "Sorry. U kunt slechts bestanden uploaden tot een grootte van 500KB";
    responseRedirect = "/forum/uploaden.jsp?message="+message;
    bytesRead = in.read(dataBytes, totalBytesRead,formDataLength);
    totalBytesRead += bytesRead;
    if (pass2==true)
    kb_size = (int)(formDataLength/1024);
    //create string from byte array for easy manipulation
    String file = new String(dataBytes);
    /*get boundary value (boundary is a unique string that separates content data)
    contentType........... multipart/form-data; boundary=---------------------------7d235ade00f0
    int lastIndex = contentType.lastIndexOf("=");
    String boundary = contentType.substring(lastIndex+1, contentType.length());
    // Stap 2.....bepaal de naam van de upload file
    // filename.............. "C:\Documents and Settings\Administrator\Desktop\boodschap.txt"
    String saveFile = file.substring(file.indexOf("filename=\"")+10);
    saveFile = saveFile.substring(0,saveFile.indexOf("\n"));
    saveFile = saveFile.substring(saveFile.lastIndexOf("\\")+1,saveFile.indexOf("\"")); //naam van de file...boodschap.txt
    String saveFileName = saveFile;
    // Stap 3..Bepaal MIME Type en de positie van eind mime type in string
    voorbeeld: -----------------------------7d23d21220524 Content-Disposition: form-data; name="file0"; filename="C:\WINNT\Profiles\mvo\Desktop\z clob.txt" Content-Type: text/plain
    String restant = "";
    int pos; //position in upload file
    // bijv .. filename="C:\Documents and Settings\Administrator\Desktop\boodschap.txt"
    pos = file.indexOf("filename=\"");
    //find position of content-disposition line
    pos = file.indexOf("\n",pos)+1; // eing file naam + spatie
    // onderstaand geeft bijv Content-Type: text/plain
    restant = file.substring(pos,file.indexOf("\n",pos)-1);
    restant = restant.substring(restant.indexOf(":")+2,restant.length()); // MIME type
    String mimeType = restant;
    //find position of eind content-type line
    pos = file.indexOf("\n",pos)+1;
    //find position of blank line
    pos = file.indexOf("\n",pos)+1;
    int start = pos;
    // Stap 4 eind boundary
    /*find the location of the next boundary marker (marking the end of the upload file data)*/
    int boundaryLocation = file.indexOf(boundary,pos)-4; //waarom -4 ..? ziet er uit als linebreak spatie--boundary=-----------------------------7d21c9ae00f0
    // Stap 5 en 6..de eigelijke te uploaden file in nieuwe byte file inserten
    byte dataBytes2[] = new byte[boundaryLocation-start]; //declareren
    for (int i=0;i<(boundaryLocation-start);i++) // inserten BELANGRIJK !!
    dataBytes2=dataBytes[start+i];
    String next_id = "0";
    Statement statement = null;
    Connection conn = null;
    boolean pass = true;
    ResultSet rs = null;
    Statement stmt_empty = null;
    oracle.sql.BLOB blb = null;
    try
    int vendor = DriverUtilities.ORACLE;
    String username = ConnectionParams.userName;
    String password = ConnectionParams.passWord;
    String connStr = DriverUtilities.makeURL(vendor);
    DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
    conn = DriverManager.getConnection(connStr,username, password);
    if (conn==null){pass=false;}
    } catch (Exception e){out.println("<P>" + "There was an error establishing a connection:");}
    if (pass==true)
    try
    String seq_nextval ="select forum_blob_seq.nextval from dual";
    statement = conn.createStatement();
    ResultSet rset = statement.executeQuery(seq_nextval);
    while (rset.next())
    next_id = rset.getString(1);
    if (next_id.equals("0"))
    message = "Uploaden mislukt !...Er ging wat fout tijdens de interactie met de database";
    responseRedirect = "/forum/uploaden.jsp?message="+message;
    pass = false;
    } catch (Exception e1) { out.println("Error blob1 : "+e1.toString()); };
    } // end pass
    if (pass==true)
    try
    Statement stmt2 = conn.createStatement();
    String insert_empty_blob = "INSERT INTO test_blob(id "+
    ",filename "+
    ",mimetype "+
    ",kb) "+
    "VALUES("+Integer.parseInt(next_id) +
    ",'"+saveFileName+"'"+
    ",'"+mimeType+"'"+
    ","+kb_size+")";
    stmt2.executeQuery(insert_empty_blob);
    conn.commit();
    if (stmt2!= null) {stmt2.close();}else{stmt2.close();pass = false;}
    } catch (Exception e2){
    message = "Uploaden mislukt !...Er ging wat fout tijdens de interactie met de database";
    responseRedirect = "/forum/uploaden.jsp?message="+message;
    out.println("<P>" + "2. There was an error inserting mime type:");}
    } //end pass
    if (pass==true)
    try
    conn.setAutoCommit(false);
    } catch (Exception e3) { pass = false; out.println("Error blob 3: "+e3.toString()); };
    } //end pass
    if (pass==true)
    try
    String Query_blob ="Select test_blob FROM test_blob where id="+next_id+" FOR UPDATE";
    stmt_empty = conn.createStatement();
    rs=stmt_empty.executeQuery(Query_blob);
    } catch (Exception e4) {
    pass = false;
    out.println("Error blob 4: "+e4.toString());
    message = "Uploaden mislukt !...Er ging wat fout tijdens de interactie met de database";
    responseRedirect = "/forum/uploaden.jsp?message="+message;};
    } //end pass
    if (pass==true)
    try
                             if (rs.next())
                             blb = ((OracleResultSet)rs).getBLOB(1);
                        OutputStream stmBlobStream = blb.getBinaryOutputStream();
                             try {
                                  int iSize = blb.getBufferSize();
                             byte[] byBuffer = new byte[iSize];
                             int iLength = -1;
    ByteArrayInputStream stmByteIn = new ByteArrayInputStream(dataBytes2);
                                  try {
    // while ( (iLength = in.read(byBuffer, 0,      iSize)) != -1 )
    while ( (iLength = stmByteIn.read(byBuffer, 0,      iSize)) != -1 )
                                       stmBlobStream.write(byBuffer, 0, iLength);
                                       stmBlobStream.flush();
                                       } // end while
    } catch (Exception e5) {
    pass=false;
    out.println("Error blob 5: "+e5.toString());
    message = "Uploaden mislukt !...Er ging wat fout tijdens de interactie met de database";
    responseRedirect = "/forum/uploaden.jsp?message="+message; }
                                  finally { conn.commit();     }
    } catch (Exception e6) { out.println("Error blob 6: "+e6.toString()); };
                             } //end if rs.next()
                             else {      throw new SQLException("Could not locate message record in database."); }
    } catch (Exception e7) { out.println("Error blob : "+e7.toString()); };
    } // end pass
    } // end pass2
    else //request is not multipart/form-data
    message = "Uploaden mislukt !...Gegevens niet verstuurd via multipart/form-data.";
    responseRedirect = "/forum/error.jsp?message="+message;
    out.println("Request not multipart/form-data.");
    catch(Exception e)
    try
    //print error message to standard out
    out.println("Error in doPost: " + e);
    //send error message to client
    out.println("An unexpected error has occurred.");
    out.println("Error description: " + e);
    }catch (Exception f) {}
    response.sendRedirect(responseRedirect);
    public void doGet(HttpServletRequest request,
    HttpServletResponse response)
    throws ServletException, IOException {
    doPost(request,response);
    Regards
    Martin

Maybe you are looking for

  • IPhoto export images w/Adobe RGB

    I shoot in RAW (Nikon), import image file to iPhoto, do some minor edits, and export to JPG (max quality) or TIFF. When I open with Preview and do COMMAND-I, I noticed the exported file now has Adobe-RGB as the color space. How I can export (from iPh

  • Oracle 11g installation on Oracle Enterprise Linux, 64bit version.

    Hi I want to install oracle 11g on Oracle Enterprise Linux, 64bit version. Do I need to set kernel parameters in this operating system, since it is not standart Linux editions. or Can I have a step by step documentation for installing oracle 11g on t

  • ALL DOWNLOADS DISTORT ALL FILES AND DESKTOP

    WINDOWS XP PRO 32. internet explorer 8. I HAVE INSTALLED AND UNINSTALLED READER AND FLASH PLAYER SEVERAL TIMES, WITH SAME RESULTS, WITH AND WITHOUT GOOGLE CHROME SELECTED. ALL Files and desktop  are so large they can not be navigated.

  • Trying to find a way to inject digital audio into an HDMI path

    There are lots of DVI to HDMI connection options out there, but I have yet to see one that allows one to incorporate digital audio into the HDMI path. Given that there are lots of early adopter video-only HDMI components out there that will be lookin

  • Will we be able to download purchased movies from the cloud?

    WE can currently download previously purchased APPS, MUSIC, and TV SHOWS.   Will we ever be able to download our purchased movies via the cloud?