Resizing an image and displaying

hi all,
i am new to graphics,
i want to resize the image (say w=300,h=300) before displaying to panel,
i tried in the following code but no help? is this current way?
in imagepanel class i am calling *"resize(image,300,300)"*. i don't know is that current way of doing, please help me to solve this problem or give any suggestion.
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class drawImage extends JFrame {
    BufferedImage orignalImage = null;
    public drawImage() {
        try {
            orignalImage = ImageIO.read(new File("C:\\Documents and Settings\\Shafi\\Desktop\\daya\\ballot\\01000361FU-0003V01.jpg"));
        } catch (Exception e) {
            e.printStackTrace();
        imagepanel imp = new imagepanel(orignalImage, 5, 5);
        //imp.resize(imp, 200,200);
        getContentPane().add(imp);
        pack();
        setVisible(true);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    public static void main(String[] arg) {
        new drawImage();
class imagepanel extends JPanel {
    private BufferedImage image;
    int x;
    int y;
    public imagepanel(BufferedImage image, int x, int y) {
        super();
        this.image = image;
        this.x = x;
        this.y = y;
        image = resize(image,300,300);
        setPreferredSize(new Dimension(image.getWidth(), image.getHeight()));
   public BufferedImage resize(BufferedImage img, int newW, int newH) { 
        int w = img.getWidth(); 
            int h = img.getHeight(); 
            BufferedImage  dimg = new BufferedImage(newW, newH, img.getType()); 
            Graphics2D g = dimg.createGraphics(); 
            g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); 
            g.drawImage(img, 0, 0, newW, newH, 0, 0, w, h, null); 
            g.dispose(); 
            return dimg; 
    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawImage(image, x, y, null);
}thanks
dayananda b v

Hey friend try this out.
public static boolean createThumbnail(String selectedCategoryName, String imagePath, String imageName){
//imagePath=full image path
//imageName=name of the image(Eg:input.jpg)
try {
int thumbHeight=100;
int thumbWidth =100;
Image image = Toolkit.getDefaultToolkit().getImage(imagePath+"/"+imageName);
MediaTracker mediaTracker = new MediaTracker(new Container());
mediaTracker.addImage(image, 0);
mediaTracker.waitForID(0);
double thumbRatio = (double)thumbWidth / (double)thumbHeight;
if(thumbRatio < 1){
thumbRatio = (double)thumbHeight / (double)thumbWidth;
int imageWidth = image.getWidth(null);
int imageHeight = image.getHeight(null);
int temp=0;
if(thumbHeight <= imageHeight || thumbWidth <= imageWidth){
double imageRatio = (double)imageWidth / (double)imageHeight;
if (thumbRatio < imageRatio) {
thumbHeight = (int)(thumbWidth / imageRatio);
} else {
thumbWidth = (int)(thumbHeight * imageRatio);
}else if(thumbHeight > imageHeight && thumbWidth > imageWidth){
thumbWidth = imageWidth + 5;
thumbHeight = imageHeight + 5;
// draw original image to thumbnail image object and
// scale it to the new size on-the-fly
BufferedImage thumbImage = new BufferedImage(thumbWidth,
thumbHeight, BufferedImage.TYPE_INT_RGB);
Graphics2D graphics2D = thumbImage.createGraphics();
graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BILINEAR);
graphics2D.drawImage(image, 0, 0, thumbWidth, thumbHeight, null);
// save thumbnail image to OUTFILE
BufferedOutputStream out = null;
out = new BufferedOutputStream(new
FileOutputStream(imagePath+"/preview_"+ imageName));
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
JPEGEncodeParam param = encoder.
getDefaultJPEGEncodeParam(thumbImage);
int quality = 100;//Integer.parseInt(args[4]);
quality = Math.max(0, Math.min(quality, 100));
param.setQuality((float)quality / 100.0f, false);
encoder.setJPEGEncodeParam(param);
encoder.encode(thumbImage);
image.flush();
thumbImage.flush();
out.flush();
out.close();
mediaTracker.removeImage(image);
mediaTracker = null;
thumbImage = null;
image = null;
encoder = null;
graphics2D = null;
System.out.println("Successfully Created Thumbnail.");
return true;
} catch (IOException ioe){
System.out.println("IO Error in writing the thumbnail:"+ ioe.getMessage());
return false;
} catch (Exception e){
System.out.println("Error in writing the thumbnail:"+ e.getMessage());
return false;
Regards..

Similar Messages

  • I want resize the image and set position after retrieving from oracle datab

    How can I display image on web page after retrieving it from oracle database. Display is not problem but resize that image and position is very dificult .Please send me Guideline about blob object todisplay and resize it in web pages

    I tried to do the suggetion made by you but I was not able to solve the issue. I think I am close to it and with your help I should be able to resolve it. Let me explain you the brief about this issue.
    1. Another group uses Oracle Apex to load the images in to the database.
    2. I am fetching this data fron Oracle and displays in to Webpage using PHP.
    This is so far I tried. Please bear with me if I am doing anything wrong.
    1.I created program.php which calls the <IMG> as suggested by you.Snippet of the code is
    <div><img src="/oracle/image_story.php" alt="Image Stories" width="900" height="500" /></div>
    2. In the image_story.php, I used the following code.
    <?php
    $query = "SELECT *
              FROM IMAGE_STORY WHERE image_id = 50";
    if ($result = run_oracle($query, 'select')) { // Run the query.
         $num_results = count($result);
         if ($num_results > 0) {
         foreach($result as $row){
              $img = $row['DOCUMT']->load();
              header("Content-type: image/pjpeg");
              echo $img;
              //echo '<div><img src="'.$img.'" alt="Image Stories" width="900" height="500" /></div>';
    ?>
    When I run the program.php,Image is not displayed and it is showing as "X". To troubleshoot the issue,I run the image_story.php and echo $img is giving me the weird character like,
    "ÿØÿàJFIFddÿìDuckyPÿîAdobedÀÿÛ„          
    I used PL/SQL developer as a client to access the BLOB field from the database and in the HTML view, it is giving me the same output.
    Select * from image_story a where a.image_id = 50
    I am not sure the issue is with the MIME-TYPE,ENCODING or I am missing something here. I tried lot of Content-Type.
    Please guide me.

  • How to compare two images and display the difference on Front Panel

    HI..
    I have attached two images.
    I want to compare these two images and subtract the differenc from these two images and display the difference(the mouse) on the front panel
    Anyone can help me?
    Really thanks
    Attachments:
    IMG_2117.JPG ‏1677 KB
    IMG_2118.JPG ‏1650 KB

    The missing thing. You have to keep in mind that what you see is not the same as the camera sees.
    So when using IMAQ Substract it gives you the difference of the value of every single pixel!
    In order to find the mouse as only difference you have to manage that every other pixel value stays the same, e.g. with a proper lightening.
    At the other hand you can combine different filters or alogorithms to get the object, e.g. if the object is darker or brighter then everything else in the image you could use a threshold and then use morphologic operations to get the objects size and position.
    Christian

  • Using Javascript & Actions to resize an image and add the filename as text

    Hello,
    I am currently working on a way to take an image, resize it and add exactly what is in it's file name (before extension) as a text layer. I have succeded in this BUT am having issues with file names that require more than one line of text.
    I need the text to align to the bottom of the image & the script or action must then resize the image so that the text does not overlap.
    Any ideas on how this can be done?
    At the moment I am using:
    -"Fit Image.jsx" to resize my image to a specific size (This was included in the Photoshop CS5 scripts)
    - A script to add the file name without extension and place the file name at a specific position.
    AdFileName.jsx
    if ( documents.length > 0 )
    var originalRulerUnits = preferences.rulerUnits;
    preferences.rulerUnits = Units.PIXELS;
    try
      var docRef = activeDocument;
      // Now create a text layer at the front
      var myLayerRef = docRef.artLayers.add();
      myLayerRef.kind = LayerKind.TEXT;
      myLayerRef.name = "Filename";
      var myTextRef = myLayerRef.textItem;
      // strip the extension off
      var fileNameNoExtension = docRef.name;
      fileNameNoExtension = fileNameNoExtension.split( "." );
      if ( fileNameNoExtension.length > 1 ) {
       fileNameNoExtension.length--;
      fileNameNoExtension = fileNameNoExtension.join(".");
      myTextRef.contents = fileNameNoExtension;
      // off set the text to be in the middle
      myTextRef.position = new Array( docRef.width / 2, docRef.height / 2 );
      myTextRef.size = 12;
            myTextRef.font="Arial-BoldMT"
            //set position of text
            myTextRef.justification = Justification.CENTER;
            myTextRef.kind = TextType.PARAGRAPHTEXT;
            myTextRef.width= docRef.width;
            myTextRef.height= docRef.height/ 2;
            myTextRef.position= [0, docRef.height * 0.88];
    catch( e )
      // An error occurred. Restore ruler units, then propagate the error back
      // to the user
      preferences.rulerUnits = originalRulerUnits;
      throw e;
    // Everything went Ok. Restore ruler units
    preferences.rulerUnits = originalRulerUnits;
    else
    alert( "You must have a document open to add the filename!" );
    Can the position be changed to allow more rows of text but keep it aligned with the bottom of the layer?
    How can I script in a way to make the image resize based on the amount of text lines?
    Any help would be greatly appreciated.

    You can add a text layer any where the only thing you need to worry about is the size of the font you use.  You can normally calculate a font size by saving the images resoltuion and then setting its resolution to 72 DPI calculate a font size basied of the images pixel width and the number of characters you want in a line. After adding the text layer you can restore the image to its original resolution and align the text layer by making a selection and alignint the text layer to the selection.  There are nine posibilites like the positions in the selection you can align to like a tick tack toe board. You need to use a script to add the text layer because your retrieving the filename.  The positioning of the text layer could be done easily in an action the would use the scriot to add a text layer the do a select all  the align the added text layer to the selection.
    About your script don't make text paragraph just add new line characters to make a multi line text layer So it can be positioned easily
    I do just that with my stampexif action.  The action uses my stampexif Photoshop java script to add a multi line text layer containing some formatted EXIF data then the action centers the text layer and add a layer style to it. Link http://www.mouseprints.net/old/dpr/StampExif.jsx Example

  • Retrieve image and display

    Hello frenz..
    can someone figure up this problem..? huhu I`m newbie in JAVA programiing try to polish my programming skill...
    character a to character z have their own picture.TGA
    if i put t picture1.tga - picture36.tga inside a folder?
    how to retrieve it ?
    example :
    character a = picture1.tga (this is a cat image)
    character b = picture2.tga (this is a dog image)
    when i enter a message : ababa
    the image display : cat dog cat dog cat ( those cat and dof is an image)

    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.BufferedImage;
    import java.io.*;
    import java.util.Random;
    import javax.imageio.ImageIO;
    import javax.swing.*;
    public class KeepingTrack extends JPanel implements ActionListener {
        BufferedImage[] images;
        String[] letters;
        String[] glyphs = new String[0];
        Random rand = new Random();
        JLabel label;
        KeepingTrack(BufferedImage[] images) {
            this.images = images;
            letters = "abcdefghijklmnop".split("(?<=[\\w])");
        public void actionPerformed(ActionEvent e) {
            int n = 5 + rand.nextInt(letters.length-4);
            glyphs = new String[n];
            String s = "";
            for(int j = 0; j < glyphs.length; j++) {
                glyphs[j] = letters[rand.nextInt(letters.length)];
                s += glyphs[j];
            // The glyphs array has been filled with the randomly
            // selected letters, ie, the "message has been entered".
            // Now, set the text in the label and draw the images
            // associated with the "message", viz, elements of the
            // glyphs array.
            label.setText(s);
            repaint();
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            int w = getWidth();
            int pad = 20;
            int n = glyphs.length;
            int cols = (w - 2*pad)/(images[0].getWidth() + pad);
            int rows = n/cols + ((n % cols > 0) ? 1 : 0);
            int x0 = pad;
            int y = pad;
            int x = x0;
            for(int j = 0; j < rows; j++) {
                for(int k = 0; k < cols; k++) {
                    int m = j*cols + k;
                    if(m > n-1) break;
                    int index = getIndexFor(glyphs[m]);
                    g.drawImage(images[index], x, y, this);
                    x += pad + images[index].getWidth();
                x = x0;
                y += images[0].getHeight() + pad;
        private int getIndexFor(String s) {
            for(int j = 0; j < letters.length; j++) {
                if(s.equals(letters[j]))
                    return j;
            return -1;
        private JPanel getTestPanel() {
            JButton button = new JButton("test");
            button.addActionListener(this);
            label = new JLabel();
            label.setHorizontalAlignment(JLabel.CENTER);
            JPanel panel = new JPanel(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.insets = new Insets(2,15,2,10);
            panel.add(button, gbc);
            gbc.weightx = 1.0;
            gbc.fill = GridBagConstraints.HORIZONTAL;
            panel.add(label, gbc);
            return panel;
        public static void main(String[] args) throws IOException {
            String prefix = "images/geek/geek";
            String[] ids = {
                "-----", "-c---", "-cg--", "-cgh-", "-cght", "-cg-t",
                "-c-h-", "-c-ht", "-c--t", "--g--", "--gh-", "--ght",
                "--g-t", "---h-", "---ht", "----t"
            BufferedImage[] images = new BufferedImage[ids.length];
            for(int j = 0; j < images.length; j++) {
                String path = prefix + ids[j] + ".gif";
                images[j] = ImageIO.read(new File(path));
            KeepingTrack test = new KeepingTrack(images);
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(test);
            f.getContentPane().add(test.getTestPanel(), "Last");
            f.setSize(600,500);
            f.setLocation(200,50);
            f.setVisible(true);
    }images found here:
    http://java.sun.com/docs/books/tutorial/uiswing/examples/components/index.html

  • Resize 4000 images and make sure they have 3 sizes of canvas

    Hi,
    I require 4000 images in 3 different sizes.
    All of the images are different sizes but they need to be resized to be a specific size.
    I know that you can set a maximum width and height, but what i want is when they are resized, to be put onto a canvas that is my specific dimension.
    Anyone know how i can do this?
    Thanks!

    You can certainly use ACDSee Pro to do this job.  4000 images is a lot to process for any computer so it will take some time but ACDSee is up to the task.  You can constrain proportions or set them to be specific pixel dimensions.
    I do not know how to use the batch functions in Fireworks since I seldom use that program.  You can check to see if Adobe Bridge can do it but it might want to open Photoshop to do the batch processing which can take some time to do.

  • How can i resize a image with changing good quality?

    i do not know how to resize a image and display to let the user view immediately.
    I hope somebody can teach me and show the completed coding

    Look at BufferedImage getScaledInstance

  • Photoshop CC: Have a template that I moved image into.  Image is too small.  How do I resize the image while in the template?  Or must I go to original image file and resize there again and again until I get the right fit?

    I have a template that I am able to plug different pictures into at different times.  The problem is that when I plug an image into that template, I find that the image is either too big or too small.  Is there a way to plug the image into the template and resize the image (and not the template itself) OR will I have to go to the file with the original image and resize it there and then try to plug it in to the template to see if it fits------and if it does not fit, go back to the original file with the image and resize it again and see if that fits---and so on and so on...........?  I have tried the" image size" option but it's hit or miss------mostly miss!
    Thanks!

    Read up on Smart Objects. It looks like you have no idea as to how to create and use them.
    Jut create a Smart Object from the layer containing whatever it image it is that you are "plugging into your template".  But you do need to learn the application at its most basic levels.
    Photoshop is a professional level application that makes no apologies for its very long and steep learning curve.  You cannot learn Photoshop in a forum, one question at a time.
    Or is it possible that you don't even have Photoshop proper but the stripped-down Photoshop Elements?"
    If the latter is the case, you're in the wrong forum.  This is not the Elements forum.
    Here's the link to the forum you would want if you're working in Elements.:
    https://forums.adobe.com/community/photoshop_elements/content
    If you do have Photoshop proper, please provide the exact version number of that application and of your OS.
    (edited for clarification)

  • Loading an image in the background and displaying it as it is loaded

    Hi,
    I'm writing an "image viewer" swing component, which should load an image in the background, and display it as it is loaded (for example each time a line of the image is loaded, display it)
    Is there a way to do this using JAI or any other api ?
    I guess i would need a way to check the loading progress from the EDT, get the loaded part of the image and display it. Am I right ? Is that possible ?
    Thanks,
    Nicolas

    In the video inspector set the Spatial Conform to "none". This will give tou the actual size of the image in the viewer. You can then use the transform controls to adjust the image to what you want to see.

  • Loading and displaying an image

    I have been able to do this with an applet quite easily
    import java.applet.Applet;
    import java.awt.Graphics;
    import java.awt.Image;
    // This is a simple example applet that loads an image and
    // displays it.
    public class DrawImage extends Applet
         Image image;
         public void init()
              image = getImage(getDocumentBase(), "cow1.jpg");
         public void paint(Graphics g)
              g.drawImage(image, 10, 10, this);
    }I haven't been able to find a good source that explains how to do it just using swing and awt. The ones I have found are complicated or don't work. I am trying to program a tester program that will load an jpg image and redraw the panel then load another jpg image so it looks like its moving. I know you can do this just using the graphic in java but I would like to do it with a jpg image files. Can anyone help with simple code for this?

    After lots of trial and error with certain classes and not knowing how to use certain methods correctly, I have this below code:
    public class image_load extends Frame
         Image img;
         public static void main (String args[])
              Toolkit toolkit = Toolkit.getDefaultToolkit();
              img = toolkit.createImage("cow1.jpg");
              img = ImageIO.read();
              ImageIcon icon = new ImageIcon("cow1.jpg",
                                     "cow pic");
              JLabel label1 = new JLabel("Image and Text", icon, JLabel.CENTER);
              JFrame frame = new JFrame();
              //set frame to exit when closed
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.add(label1);     //add panel to frame
              frame.setSize(25,25);     //set size of frame to 300pix x300pix
              frame.setVisible(true);     //make frame visable
         public void paint(Graphics graphics) {
              graphics.drawImage(img, 0, 0, null);
    }I get these errors from the code:
    image_load.java:21: non-static variable img cannot be referenced from a static c
    ontext
                    img = toolkit.createImage("cow1.jpg");
                    ^
    image_load.java:23: non-static variable img cannot be referenced from a static c
    ontext
                    img = ImageIO.read();
                    ^
    image_load.java:23: cannot find symbol
    symbol  : method read()
    location: class javax.imageio.ImageIO
                    img = ImageIO.read();
                                 ^
    3 errorsI have tried a contructor and other things. As for the imageIO.read error that only accepts in Buffered Images. For this I have this odd bit of code that needs changing to be able to work. Any more suggestions?
    BufferedImage bufferedImage = new BufferedImage ( imageWidth,
                                                      imageHeight,
                                                      BufferedImage.TYPE_INT_BGR  );
              bufferedImage.createGraphics().drawImage( image, 0, 0, this);

  • AppleScript to resize images and save with new name

    I want to make an apple script, which resizes all images of a folder regardless what kind of filetype.
    The source folder will change every day.
    With the script i want to choose a source Folder, resize all images and save the files with my jpeg options in the same folder, but with adding  „_ipad“ in the filename.
    I tried to edit an existing script from this forum, but in Photoshop 5.1 i get the error-message "This function is possibly not available in this Version" in line 18 "save in file newFileName as JPEG with options myOptions"
    How can i save the documents with new name in the existing folder?
    Thanks.
    This is the script i’m working with:
    set inputFolder to choose folder with prompt "Wähle einen Ordner:"
    --set destinationFolder to choose folder with prompt "Wähle einen Zielordner" as string
    tell application "Finder"
              set filesList to (files of entire contents of inputFolder) as alias list
    end tell
    tell application "Adobe Photoshop CS5.1"
              set UserPrefs to properties of settings
              set ruler units of settings to pixel units
              repeat with aFile in filesList
      open aFile showing dialogs never
                        set docRef to the current document
                        tell docRef
                                  set newFileName to my getBaseName(name)
      --resize image height 240 resolution 72 resample method bicubic sharper
      change mode to RGB
      resize image resolution 72
                                  set myOptions to {class:JPEG save options, embed color profile:true, quality:12, format options:progressive, scans:3}
      save in file newFileName as JPEG with options myOptions
                        end tell
      close the current document saving no
              end repeat
              set ruler units of settings to ruler units of UserPrefs
    end tell
    on getBaseName(fName)
              set baseName to fName
              repeat with idx from 1 to (length of fName)
                        if (item idx of fName = ".") then
                                  set baseName to (items 1 thru (idx - 1) of fName) as string
                                  exit repeat
                        end if
              end repeat
              return baseName
    end getBaseName

    This seems like a Photoshop error not an AppleScript one. Have you looked in the Photoshop dictionary to see if the command you are getting the error on exists and if it has those options?
    If all you want to do is resize image files and save the resized image file you might want to look at Automator. Specifically the Scale Image action under Photos.
    regards

  • Storing and displaying LOB - pdf, images

    Hi,
    I am using Oracel 10g on Linux.
    I need to store pdfs and images and display them using HTMLDB reports and Discoverer reports. the LOBs size vary from 30KB to 1700KB.
    Which will be the best way to store these objects. since the sizes are not that big, i was thinking of storing them directly in the database tables instead of storing them externally.
    and storing internally in the database, will it be better for a quick retrieval and display of the LOB in the reports.
    Can somone guide me and maybe link me to some documents for storing LOB and displaying using HTMLDB and Discoverer.
    Thanks,
    Philip.

    Whether you store the documents in the database or not is totally dependent on your requirements (backup, security, etc). As for performance, you may need to test that for yourself once you have it configured.
    You may want to walk through this How to Upload and Download Files in an Application. It provides detailed instructions for facilitating what you are looking for in Application Express (formerly HTMLDB).

  • How to use the Rectangle class to draw an image and center it in a JPanel

    I sent an earlier post on how to center an image in a JPanel using the Rectangle class. I was asked to send an executable code which will show the malfunction. The code below is an executable code and a small part of a very big project. To simplifiy things, it is just a JFrame and a JPanel with an open dialog. Once executed the JFrame and the FileDialog will open. You can then navigate to a .gif or a .jpg picture and open it. What I want is for the picture to be centered in the middle of the JPanel and not the upper left corner. It is also important to stress that, I am usinig the Rectangle class to draw the Image. The region of interest is where the rectangle is created. In the constructor of the CenterRect class, I initialize the Rectangle class. Then I use paintComponent in the CenterRect class to draw the Image. The other classes are just support classes. The MyImage class is an extended image class which also has a draw() method. Any assistance in getting the Rectangle to show at the center of the JPanel without affecting the size and shape of the image will be greatly appreciated.
    I have divided the code into three parts. They are all supposed to be on one file in order to execute.
    import java.awt.*;
    import java.awt.image.*;
    import javax.swing.*;
    public class CenterRect extends JPanel {
        public static Rectangle srcRect;
        Insets insets = null;
        Image image;
        MyImage imp;
        private double magnification;
        private int dstWidth, dstHeight;
        public CenterRect(MyImage imp){
            insets = getInsets();
            this.imp = imp;
            int width = imp.getWidth();
            int height = imp.getHeight();
            ImagePanel.init();
            srcRect = new Rectangle(0,0, width, height);
            srcRect.setLocation(0,0);
            setDrawingSize(width, height);
            magnification = 1.0;
        public void setDrawingSize(int width, int height) {
            dstWidth = width;
            dstHeight = height;
            setSize(dstWidth, dstHeight);
        public void paintComponent(Graphics g) {
            Image img = imp.getImage();
         try {
                if (img!=null)
                    g.drawImage(img,0,0, (int)(srcRect.width*magnification), (int)(srcRect.height*magnification),
              srcRect.x, srcRect.y, srcRect.x+srcRect.width, srcRect.y+srcRect.height, null);
            catch(OutOfMemoryError e) {e.printStackTrace();}
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new Opener().openImage();
    class Opener{
        private String dir;
        private String name;
        private static String defaultDirectory;
        JFrame parent;
        public Opener() {
            initComponents();
         public void initComponents(){
            parent = new JFrame();
            parent.setContentPane(ImagePanel.panel);
            parent.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
            parent.setExtendedState(JFrame.MAXIMIZED_BOTH);
            parent.setVisible(true);
        public void openDialog(String title, String path){
            if (path==null || path.equals("")) {
                FileDialog fd = new FileDialog(parent, title);
                defaultDirectory = "dir.image";
                if (defaultDirectory!=null)
                    fd.setDirectory(defaultDirectory);
                fd.setVisible(true);
                name = fd.getFile();
                if (name!=null) {
                    dir = fd.getDirectory();
                    defaultDirectory = dir;
                fd.dispose();
                if (parent==null)
                    return;
            } else {
                int i = path.lastIndexOf('/');
                if (i==-1)
                    i = path.lastIndexOf('\\');
                if (i>0) {
                    dir = path.substring(0, i+1);
                    name = path.substring(i+1);
                } else {
                    dir = "";
                    name = path;
        public MyImage openImage(String directory, String name) {
            MyImage imp = openJpegOrGif(dir, name);
            return imp;
        public void openImage() {
            openDialog("Open...", "");
            String directory = dir;
            String name = this.name;
            if (name==null)
                return;
            MyImage imp = openImage(directory, name);
            if (imp!=null) imp.show();
        MyImage openJpegOrGif(String dir, String name) {
                MyImage imp = null;
                Image img = Toolkit.getDefaultToolkit().getImage(dir+name);
                if (img!=null) {
                    imp = new MyImage(name, img);
                    FileInfo fi = new FileInfo();
                    fi.fileFormat = fi.GIF_OR_JPG;
                    fi.fileName = name;
                    fi.directory = dir;
                    imp.setFileInfo(fi);
                return imp;
    }

    This is the second part. It is a continuation of the first part. They are all supposed to be on one file.
    class MyImage implements ImageObserver{
        private int imageUpdateY, imageUpdateW,width,height;
        private boolean imageLoaded;
        private static int currentID = -1;
        private int ID;
        private static Component comp;
        protected ImageProcessor ip;
        private String title;
        protected Image img;
        private static int xbase = -1;
        private static int ybase,xloc,yloc;
        private static int count = 0;
        private static final int XINC = 8;
        private static final int YINC = 12;
        private int originalScale = 1;
        private FileInfo fileInfo;
        ImagePanel win;
        /** Constructs an ImagePlus from an AWT Image. The first argument
         * will be used as the title of the window that displays the image. */
        public MyImage(String title, Image img) {
            this.title = title;
             ID = --currentID;
            if (img!=null)
                setImage(img);
        public boolean imageUpdate(Image img, int flags, int x, int y, int w, int h) {
             imageUpdateY = y;
             imageUpdateW = w;
             imageLoaded = (flags & (ALLBITS|FRAMEBITS|ABORT)) != 0;
         return !imageLoaded;
        public int getWidth() {
             return width;
        public int getHeight() {
             return height;
        /** Replaces the ImageProcessor, if any, with the one specified.
         * Set 'title' to null to leave the image title unchanged. */
        public void setProcessor(String title, ImageProcessor ip) {
            if (title!=null) this.title = title;
            this.ip = ip;
            img = ip.createImage();
            boolean newSize = width!=ip.getWidth() || height!=ip.getHeight();
         width = ip.getWidth();
         height = ip.getHeight();
         if (win!=null && newSize) {
                win = new ImagePanel(this);
        public void draw(){
            CenterRect ic = null;
            win = new ImagePanel(this);
            if (win!=null){
                win.addIC(this);
                win.getCanvas().repaint();
                ic = win .getCanvas();
                win.panel.add(ic);
                int width = win.imp.getWidth();
                int height = win.imp.getHeight();
                Point ijLoc = new Point(10,32);
                if (xbase==-1) {
                    xbase = 5;
                    ybase = ijLoc.y;
                    xloc = xbase;
                    yloc = ybase;
                if ((xloc+width)>ijLoc.x && yloc<(ybase+20))
                    yloc = ybase+20;
                    int x = xloc;
                    int y = yloc;
                    xloc += XINC;
                    yloc += YINC;
                    Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
                    count++;
                    if (count%6==0) {
                        xloc = xbase;
                        yloc = ybase;
                    int scale = 1;
                    while (xbase+XINC*4+width/scale>screen.width || ybase+YINC*4+height/scale>screen.height)
                        if (scale>1) {
                   originalScale = scale;
                   ic.setDrawingSize(width/scale, height/scale);
        /** Returns the current AWT image. */
        public Image getImage() {
            if (img==null && ip!=null)
                img = ip.createImage();
            return img;
        /** Replaces the AWT image, if any, with the one specified. */
        public void setImage(Image img) {
            waitForImage(img);
            this.img = img;
            JPanel panel = ImagePanel.panel;
            width = img.getWidth(panel);
            height = img.getHeight(panel);
            ip = null;
        /** Opens a window to display this image and clears the status bar. */
        public void show() {
            show("");
        /** Opens a window to display this image and displays
         * 'statusMessage' in the status bar. */
        public void show(String statusMessage) {
            if (img==null && ip!=null){
                img = ip.createImage();
            if ((img!=null) && (width>=0) && (height>=0)) {
                win = new ImagePanel(this);
                draw();
        private void waitForImage(Image img) {
        if (comp==null) {
            comp = ImagePanel.panel;
            if (comp==null)
                comp = new JPanel();
        imageLoaded = false;
        if (!comp.prepareImage(img, this)) {
            double progress;
            while (!imageLoaded) {
                if (imageUpdateW>1) {
                    progress = (double)imageUpdateY/imageUpdateW;
                    if (!(progress<1.0)) {
                        progress = 1.0 - (progress-1.0);
                        if (progress<0.0) progress = 0.9;
    public void setFileInfo(FileInfo fi) {
        fi.pixels = null;
        fileInfo = fi;
    }

  • Problem in showing progress image and status message.

    Hi, friends,
    I have file upload program in which when user uploads the file
    i want to show animated progress file
    i.e. ( circle.gif )
    when upload finishes it should display message :
    File < file name > uploaded successfully.
    How do i achieve it ?
    since when i am uploading file , image is displayed but
    due to upload process image is hanged up and did not showing
    animation.
    Kindly solve the above problem.
    i post my some code here.
    ============================
    javascript part is here
    function showProgress()
            document.getElementById('imgprogress').style.display = "";
         document.getElementById('imgprogress').style.visibility="";
        function completedupload()
         document.getElementById('progress').style.display = "";
         document.getElementById('progress').style.visibility="";
    <div id="imgprogress" style="display:none; visibility:hidden;"><img src="images/circle.gif"></div>
                                                      <div id="progress" style="display:none; visibility:hidden;"><%= status %></div>
                                                      <div id="" style="display:none; visibility:hidden; "><img src="images/circle.gif" width="21" height="21"></div>since it is not working good.
    please provide me good solution for this.
    i need exactly following :
    when user gives big file to upload it shows progress as animated image
    and upload process finished up, it should remove image and display status message like " File Upload completed. "

    I know this is an old topic, but I found the solution and thought I'd share it! By default, a JList only has 1 visible row. To allow the number of rows to expand dynamically, throw this in.
    this.imageList.setVisibleRowCount(-1);My code looks like this. It centers each image and centers the text under the image and wraps images horizontally.
        ListCellRenderer renderer = new ImageListCellRenderer();
        this.imageList.setCellRenderer(renderer);
        DefaultListModel listModel = new DefaultListModel();
        this.imageList.setVisibleRowCount(-1);
        this.imageList.setLayoutOrientation(JList.HORIZONTAL_WRAP);
        this.imageList.setModel(listModel);and the renderer
    public class ImageListCellRenderer extends DefaultListCellRenderer { 
      public Component getListCellRendererComponent(JList list, Object value, int
          index, boolean isSelected, boolean hasFocus) {
        JLabel label = (JLabel)super.getListCellRendererComponent(list, value,
            index, isSelected, hasFocus);
        if (value instanceof File) {
          File imageFile = (File)value;
          String path = imageFile.getAbsolutePath();
          Image image = Toolkit.getDefaultToolkit().getImage(path);
          image = image.getScaledInstance(100, 100, Image.SCALE_DEFAULT);
          ImageIcon imageIcon = new ImageIcon(image);
          label.setIcon(imageIcon);
          label.setText(path.substring(path.lastIndexOf(File.separatorChar) + 1));
          label.setVerticalTextPosition(SwingConstants.BOTTOM);
          label.setHorizontalAlignment(SwingConstants.CENTER);
          label.setHorizontalTextPosition(SwingConstants.CENTER);
        else {
          label.setIcon(null);
        return label;
    }I need to work on this to improve performance, but it works!

  • How can I resize an image in Preview?

    There has been lots of discussion about Preview but non really answers my question. If I resize an image and duplicate it the duplicate over rides the settings of the original - so now I have 2 images the same size which is not what I want. I want the new image smaller but to keep the original the same size as before resizing. Versions seem to do the same thing, and as far as I can make out so does export. I know you can revert one of the duplicate images to get it back to the original size but it is a rather convoluted process.
    I know there are very clever people here so perhaps one of you can give me a work flow to do what I require. Thanks in advance.

    Of course, you can save some steps by duplicating the original file first, and then resize the copy.
    rolando

Maybe you are looking for

  • XMLP print - two steps or one step?

    When we were in 11.5.9 + XMLP 4.5 (with XMLP and CM integrated configuration), to print concurrent reports via XMLP always two steps. namely, the first step produces XML file and the second step is running XML Publisher Report to feed the XML file to

  • Login problem to oracle 10g

    Hi all, I have installed the oracle 10g (Oracle Database 10g Release 1 (10.1.0.2) for Microsoft Windows (32-bit) ).The installation was sucessful and I created the same password for all the default accounts.I left everything for default like Global D

  • Audio Dropouts help!?

    Hi forum, Hope someone can help me out with this as I'm working on a big project with a deadline...  Strangely ceratin tracks are dropping out here and there for no apparent reason.  Unfortunately, I can't muck about with the buffer settings as East

  • On deployment, Param window says"The report requested requires further info

    Development environment has Windows 7 VS2010 with Crystal Service pack 2 (just upgraded). The web application is .Net 3.5 32bit. The production environment is windows 2003 - IIS6.0. The target database is SQL Server express 2008 . On the page load, t

  • Modify existing query in Discoverer Report

    Hi, 1) I want to put an outer join to the existing discoverer work sheet query. Is there any way I could do it. 2) I am trying to modify the query by Export and Import options in the Discoverer Desktop and I am getting the below error. All I did was