Get Image's bytes

Hi people,
I'm trying to get the bytes from an image. I know the complete path to that image, and I know the image's name also, so I pass the image's whole name as a String to a method wich will read the bytes. When I try to read the image's bytes I get the following meassures: width = -1, height = 0.
This is the code I use:
  int err = imageReturn(path + "/" + img);
  byte[] b2bytes = b2.toByteArray();
public int imageReturn(String imagePath){
    //path is c:\javi\image.jpg
    try{
        int w,h;
        Image img = null;
        img = Toolkit.getDefaultToolkit().getImage(imagePath);
        w = img.getWidth(null);
        h = img.getHeight(null);
System.out.println("image size: " + w + "x" + h); //--> print's -1x0!!!
        BufferedImage finalImage = new BufferedImage(w, h, 
                                            BufferedImage.TYPE_INT_RGB);
        finalImage.createGraphics().drawImage(img, 0, 0, null);
        b2 = new ByteArrayOutputStream(); //global
        JPEGImageEncoder encoder=JPEGCodec.createJPEGEncoder(b2);
        JPEGEncodeParam param=encoder.getDefaultJPEGEncodeParam
                                                           (finalImage);
        param.setQuality(1.0f, false);
        encoder.setJPEGEncodeParam(param);
        encoder.encode(finalImage);
        b2.close();
        return(0);
    }catch(Exception e){
        System.out.println(e.toString());
        return(-1);
}//imageReturnAs you see, the goal is to get a byte[] with the image information. I don't know if there's any other way (simpler one) to solve it. Any help will be appreciated.
Thanks all,
Javi

The problem really is withe the Image class, which was never intended for this sort of thing. If you use the ImageIO classes, you can get BufferedImages direct from jpg files, and then you have access to the underlying buffers:
import java.io.*;
import javax.imageio.*;
import java.awt.image.*;
public class FileOperations
    public static BufferedImage readImageFromFile(File file) throws IOException
        return ImageIO.read(file);
    public static void writeImageToFile(File file,BufferedImage bufferedImage) throws IOException
        ImageIO.write(bufferedImage,"JPG",file);
}

Similar Messages

  • Images, Thumbnails, byte[ ] and BLOB

    Hi guys,
    This is what I have to do:
    User selects image from disk and i'm putting it into DB (IBM DB2 8.0). That's clear. No problem.
    But I need that image as a thumbnail as well (I have to show images as thumbnails for each Item). I have a DB table IMAGE with 2 columns - IMAGE_FULL and IMAGE_THUMBNAIL.
    So I need to scale image(wich I have as byte array, or struts FormFile) and than put it into DB as Thumbnail.
    Or even if I don't have IMAGE_THUMBNAIL column, I have to get image as byte array from IMAGE_FULL column, scale it and show it in the browser.
    So, if I explained correctly and not very complicated way, can anyone give some ideas?
    Thanks in advance
    Gio

    For thumbnails, there's plenty of examples of resizing and saving images in the Java Programming forum, just do a search.
    For the database storage and retrieval... I had found some really good site with database examples, but I can't find it anymore.... but here's some code:
    // store
                   PreparedStatement pstmt = db.getConnection().prepareStatement(
                        "INSERT INTO TeeColor VALUES( ?, ? )" );
                   pstmt.setString(1, "yellow");
                   File fImage = new File("yellow.gif");
                   InputStream isImage = new FileInputStream(fImage);
                   pstmt.setBinaryStream(2, isImage, (int)fImage.length());
                   int res = pstmt.executeUpdate();
    // load
                   Statement stmt = db.getConnection().createStatement();
                   ResultSet rs = stmt.executeQuery(
                        "SELECT TCBlob FROM TeeColor WHERE TColor = 'Yellow'");
                   if(rs.next()) {
                        byte[] bytes = rs.getBytes("TCBlob");
                        JFrame f = new JFrame("test");
                        f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                        f.getContentPane().add(new JLabel(new ImageIcon(bytes)));
                        f.pack();
                        f.show();
                   }

  • Problem with getting resized image's bytes

    I've got a problem with getting correct bytes of a newly resized image. The flow is that I retrive an image from the filesystem. Due to the fact that it is large I resize it to a 50x50px thumbnail. I can display this thumbnail in #benchmark1 (see code below). Unfortunately something's wrong with my imageToBytes funtion which returns reasonably small size of image but is totally useless - I can't make an image of it anymore so at #benchmark2 the application either crashes or keeps freezing. I saved this byte array on my disk and tried to preview under Windows how does it look but I got a message "Preview unavailabe". I did some digging in the Internet and I supposed that it's because I don't use any jpg or png encoders to save the file. Actually I think that it's not the case, as the bytes returned from method imageToBytes look weird - I cannot even make a new image of them and display it without any saving in memory.
                                  byte[] bytes = FileHandler.readFile (
                                          FileHandler.PHOTOS_PATH, fileName);
                                  Image img2 = Image.createImage (bytes, 0, bytes.length);
                                  img2 = ImageHandler.getInstance ().resize (img2);
                                                    //#benchmark1
                                  bytes = ImageUtils.imageToBytes (img2);
                                  img2 = Image.createImage (bytes, 0, bytes.length);
                                                    //#benchmark2my imageToBytes function is as follows:
         public static byte[] imageToBytes (Image img)
              int[] imgRgbData = new int[img.getWidth () * img.getHeight ()];
              byte[] imageData = null;
              try
                   img.getRGB (imgRgbData, 0, img.getWidth (), 0, 0, img.getWidth (),
                           img.getHeight ());
              catch (Exception e)
              ByteArrayOutputStream baos = new ByteArrayOutputStream ();
              DataOutputStream dos = new DataOutputStream (baos);
              try
                   for (int i = 0; i < imgRgbData.length; i++)
                        dos.writeInt (imgRgbData);
                   imageData = baos.toByteArray ();
                   baos.close ();
                   dos.close ();
              catch (Exception e)
              return imageData;
    I've run totally out of any idea what's wrong, please help!
    Edited by: crawlie on Jul 17, 2010 6:21 PM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

    Hey Crawlie,
    Please note that simply writing int values into ByteArrayOutputStream will not suffice. Please have a look at the following conversion from int pixel value into byte[4]:
    public static final byte[] intToByteArray(int value) {
            return new byte[] {
                    (byte)(value >>> 24),
                    (byte)(value >>> 16),
                    (byte)(value >>> 8),
                    (byte)value
    }Good Luck!
    Daniel

  • How to get image size in bytes

    i have to get image size in bytes and accessing image from the a folder
    Thanks in advance

    If it's going to be accessed as a file on the filesystem, you can use java.io.File.length() to get the size in bytes.
    In other situations...it depends on what you're doing.

  • Create image from byte[]array on server side

    Hello everyone..
    I'm developing an application which will take snapshots from a mobile device, and send it to my pc via bluetooth. I have my own midlet which uses the phone camera to take the snapshot, i want to transfer that snapshot to my pc.
    The snapshot is taken is stored in an array byte.
    The image can be created on the phone itself with no problem using : image.createImage(byte[])
    my problem is that when i send the array byte via bluetooth, and receive it on the server, i cannot create the image using the :image.createImage() code
    The connection is good since i have tested by writing the content of the array in a text file.
    Piece of midlet code:
                try{
                     stream = (StreamConnection)Connector.open(url);
                     OutputStream ggt = stream.openOutputStream();
                     ggt.write(str);
                     ggt.close();
                }catch(Exception e){
                     err1  = e.getMessage();
                }where str is my array byte containing the snapshot
    And on my server side:
    Thread th = new Thread(){
                   public void run(){
                        try{
                             while(true){
                                  byte[] b = new byte[in.read()];
                                  int x=0;
                                  System.out.println("reading");
                                  r = in.read(b,0,b.length);
                                  if (r!=0){
                                       System.out.println(r);     
                                       img = Image.createImage(b, 0, r);
                                                            //other codes
                                       i get this error message:
    Exception in thread "Thread-0" java.lang.UnsatisfiedLinkError: javax.microedition.lcdui.ImmutableImage.decodeImage([BII)V
         at javax.microedition.lcdui.ImmutableImage.decodeImage(Native Method)
         at javax.microedition.lcdui.ImmutableImage.<init>(Image.java:906)
         at javax.microedition.lcdui.Image.createImage(Image.java:367)
         at picserv2$1.run(picserv2.java:70)
    Please anyone can help me here? is this the way to create the image on the server side? thx a lot

    here is exactly how i did it :
    while(true){
                                  byte[] b = new byte[in.read()];
                                  System.out.println("reading");
                                  r = in.read(b, 0, b.length);
                                  if (r!=0){
                                       Toolkit toolkit = Toolkit.getDefaultToolkit();
                                       Image img = toolkit.createImage(b, 0, b.length);
                                       JLabel label = new JLabel(new ImageIcon(img) );
                                       BufferedImage bImage = new BufferedImage(img.getWidth(label),img.getHeight(label),BufferedImage.TYPE_INT_RGB);
                                       bImage.createGraphics().drawImage(img, 0,0,null);
                                       File xd = new File("D:/file.jpg");
                                       ImageIO.write(bImage, "jpg", xd);
                                       System.out.println("image sent");
                             }Edited by: jin_a on Mar 22, 2008 9:58 AM

  • Display image from byte array

    Hello Everybody,
    I need to display an image given in a byte array, how can I show this image in a JFrame?
    1. I tryied saving the image in a .jpg file,
         File file1 = new File("Path to my destination image");2. then I use a FileOutputStream to save the image in the path:
            FileOutputStream fos1 = new FileOutputStream(docu);
            fos1.write(ImageInbyteArray);
            fos1.close();3. Once I have the image in a file I'm trying to load it using a JButton, but the JButton doesn't display the image. I think that for some unknown (at least for me ;-) reason the file isn't still available to be used in the ImageIcon, this is my code:
            imgIconDocu = new ImageIcon("Path to my destination image");
            jBtnDocu = new JButton(imgIconDocu);What's wrong here?
    Thanks a lot

    Does the byte array contain a JPEG image? Where did
    you get the contents of the byte array?yes the array contains the JPEG image, I have a database in PostgreSQL, and the images are stored in blob in the database. I have to call a service in the server and in return it gives me the 3 images as byte arrays, that's the reason I only have the byte arrays. so I tryed saving the images as jpeg files in my hard disk to show them, but it appears that they are not available to show them in Swing after saving them. I can only show the images if I close my application and start it again :-(
    I tryed flushing and closing the FileOutputStream after the writting process (fos.write(bytearrayImage);
    fos.flush();
    fos.close();)
    Y also tryed:
    fos.write(bytearrayImage);
    fos.close();
    fos.flush();But it doesn't work either :-(
    What do you recommend me?.
    Thanks a lot,
    Johnny G L

  • Image to byte array

    hello,
    how can i get an image in jar file as a byte[] or can i convert an image to byte[]?
    thx...

    To read a bytes from a jar file, use a JarInputStream. If you're just trying to read bytes from a jar, it doesn't make any difference whether it's an image or not.
    To get the bytes from an Image, you need to put more information in your question - are you talking about an image file, like a JPEG or TIFF? What do you want to do with it? Or are you talking about an Image object in Java? If so, which specific concrete subclass, and what do you want to do with it?

  • Exception getting blob to byte[]

    Hy guys,
    I 've a problem with my java application.
    I use hibernate to interact with a derby database.
    I stored a image into blob field (and no problem).
    When I try to get blob to array of byte I've this exception:
    java.sql.SQLException: You cannot invoke other java.sql.Clob/java.sql.Blob methods after calling the free() method or after the Blob/Clob's transaction has been committed or rolled back.To get blob I did
    Blob cThumnb = ((Allegato) cAllegati.get(i)).getThumb();
    byte[] cPrev = toByteArray(cThumnb);where
    private byte[] toByteArray(Blob fromBlob) {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            try {
                return toByteArrayImpl(fromBlob, baos);
            catch (SQLException e)
                throw new RuntimeException(e);
            catch (IOException e)
                throw new RuntimeException(e);
            finally
                if (baos != null)
                    try
                        baos.close();
                    catch (IOException ex)
        private byte[] toByteArrayImpl(Blob fromBlob, ByteArrayOutputStream baos)  throws SQLException, IOException
            byte[] buf = new byte[4000];
            InputStream is = fromBlob.getBinaryStream();
            try
                for (;;)
                    int dataSize = is.read(buf);
                    if (dataSize == -1)     break;
                    baos.write(buf, 0, dataSize);
            catch(IOException ex)
                    throw ex;
           finally
                if (is != null)
                    try
                        is.close();
                    catch (IOException ex)
                    return  buf;// baos.toByteArray();
        }Could you help me?
    I set also autocommit to false,
    Thanks,
    Regards

    EJP wrote:
    So could you cite some references that show, in general, that one normally needs to process blobs as streams?The design. The name, which is an acroynm for Binary Large Object. The fact that they have a stream interface, like files and sockets.The idiom for loading does not require nor even recommend that one must process as a stream.
    And most of the time I do not process files nor sockets via streaming methodologies. I load them entirely, then process them.
    Actually for direct socket usage, excluding protocols like FTP, I don't believe I have ever streamed processing because in message based protocols the messages are very small.
    Presumably because the OP has one reference to 'thumb' as in thumbnail view?From the OP's first post: 'I stored a image into blob field'.I see. I have stored images in databases before. Excluding storage of medical media files they were all processed in memory because all were rather small.
    Certainly cases where one does in fact want to read an entire file into memory, before one starts processing it.Can't think of any, but in any case if you are able to process it as a stream you are wasting both time and space by not doing so.If I have any data that is in fact "large" I will keep that in mind. But, for example, I can't see processing a configuration file that consists of a couple hundred bytes via stream processing just because files allow for the possibility that one can process a large file.

  • Java image and byte[]

    I am having trouble writing and reading data from an image. I am using the following code to get the bytes for a picture.
    BufferedImage pic = ImageIO.read(new File(picture));
    WritableRaster writableRaster = pic.getRaster();
    DataBufferByte buffer = (DataBufferByte)writableRaster.getDataBuffer();
    byte[] picBytes = buffer.getData();After making some changes I would like to write the new bytes to a file. This seems to work as the new picture shows the changes when I look at it.
    File newFile = new File("C:/NewPic.jpg");
    ImageIO.write(pic,"jpg",newFile);However, when I try to read the newFile using the same method as above I do not get the same bytes. I am using the following code to print the bytes in hex to verify what they are.
    BufferedWriter out2 = new BufferedWriter(new FileWriter("pix2.txt"));
    for(int x=0; x<picBytes.length; x++)
    out2.write((Integer.toString(picBytes[x] & 0xff, 16).toUpperCase()+" "));
    }This produces:
    7F 7F 7F 7F 7F 7F 7F 7F 7F 7F 7F 7F 7F 7F 7F 7F
    7F 7F 7F 7F 7F 7F 7F 7F 7F 7F FF FF 7F FF FF FF
    for the bytes that I have made the changes to, and when I try to read from the newly created file I get:
    82 7F 7A 82 7F 7A 82 7E 7D 82 7E 7D 82 7D 7F 82
    7D 7F 82 7B 82 82 7B 82 AC A5 AC B4 AE B3 E0 DA
    but there is nothing wrong with the picture. Do I need to create a new BufferedImage before I save, or what could be causing this change?

    Hmmm... I'm not sure what you are doing or what your goal is, but are you aware that JPEGs tend to use a losey compression?

  • Rich text box used in Infopath Form not displaying option to get images from Computer

    Hello,
    We have used "Rich text box" in Infopath Form which is not displaying option to get images from Computer.
    Options available are : From Address, From SharePoint
    But if we Rich text box in list, then it works fine with "From Computer" option.
    can you please help me out to get this option.
    Thanks in advance.
    REgards,
    Jayashri

    Hi,
    From your description, there is no “From Computer” option to get images with rich text box in InfoPath form.
    Per my knowledge, by design there are “From Address” and “From SharePoint” options without “From Computer” option in rich text box in InfoPath form. As a workaround, you can develop a custom InfoPath Rich Text box to do it.
    About developing a custom InfoPath control, I suggest you create a new thread on the forum “Visual Studio Tools for Office”, more experts will assist you with InfoPath development.
    Visual Studio Tools for Office:
    https://social.msdn.microsoft.com/Forums/office/en-US/home?forum=vsto&filter=alltypes&sort=lastpostdesc
    Thanks,
    Dean Wang

  • When browsing a new library that I created, the browser shows dotted lines around grey rectangles, no images. When I double click on a rectangle the image appears. How do I get images to appear in the browser rectangles?

    When browsing a new library that I created and exported onto an external hard drive, the browser shows dotted lines around grey rectangles, no images. When I double click on a rectangle, the image appears, but all the other rectangles remain empty - no image. How do I get images to appear in the browser rectangles? I am viewing this on a second computer (an older intel duo iMac), not the one I created the library on (a MacBook Pro). Both computers have Aperture 3.2.4 installed. When I return the external to the MacBook, all images appear in browser rectangles. What's happening on the iMac?

    You may have a problem with the permissions on your external volume. Probably you are not the owner of your library on the second mac.
    If you have not already done so, set the "Ignore Ownership on this Volume" flag on your external volume. To do this, select the volume in the Finder and use the Finder command "File > Get Info" (or ⌘I).
    In the "Get Info" panel disclose the "Sharing & Permissions" brick, open the padlock, and enable the "Ignore Ownership on this Volume" flag. You will have to authentificate as administrator to do this.
    Then run the "Aperture Library First Aid Tools" on this library and repair the permissions. To launch the "First Aid Tools" hold down the ⌥⌘-key combination while you double click your Aperture Library. Select "Repair Permissions" and run the repair; then repeat with "Repair Database". Do this on the omputer where you created the library and where you can see the thumbnails.
    Then check, if you now are able to read the library properly on your iMac.
    Regards
    Léonie

  • Error while getting  image from database in SUP using ios?

    Hi All,
      Im developing native iOS application using sup 2.1.3 . Im getting error While retrieving  image from SUP database. Here i'm trying to get image from database and show in imageView.can any one help me how to fix this issue?
    In database image datatype is  'LONG Binary' .
    My table Schema:
    CREATE TABLE dba.ImagesTable (
    RowID INT NOT NULL,
    ImageName VARCHAR(20) NOT NULL,
    PhotoData LONG BINARY NOT NULL,
    IN SYSTEM
    ALTER TABLE dba.ImagesTable
      ADD CONSTRAINT ASA137 PRIMARY KEY CLUSTERED (RowID)
    ALTER TABLE dba.ImagesTable
      ADD CONSTRAINT ASA138 UNIQUE NONCLUSTERED (RowID)
    in Xcode:
                [SUP107SUP107DB synchronize];
                SUP107ImagesTable *imgTable =[[SUP107ImagesTable alloc]init];
                SUP107ImagesTableList *list =[SUP107ImagesTable findAll];
                SUP107ImagesTable * oneRecord =[list objectAtIndex:0];
                NSLog(@"rowId:%d---imageName:%@---photoData:%@---photoLenght:%d",oneRecord.rowID,oneRecord.imageName,oneRecord.photoData,oneRecord.photoDataLength);
                NSData *tempData =[[NSData alloc]init];
                SUPBigBinary *responseBinaryData = (SUPBigBinary *)oneRecord.photoData.value;
                @try {
                    [responseBinaryData openForWrite:[oneRecord.photoData length]];
                    [responseBinaryData write:tempData];
                @catch (NSException *exception) {
                    NSLog(@"exception: %@",[exception description]);
                UIImageView *imgView =[[UIImageView alloc] initWithFrame:CGRectMake(50,50,100,100)];
                [self.window addSubview:imgView];
                UIImage * tempImage =[UIImage imageWithData:tempData];
                imgView.image = tempImage;
                [responseBinaryData close];
    Error Log:
    2014-04-02 18:42:15.150 SUP102[2873:70b] rowId:1---imageName:Apple---photoData:SUPBigBinary: column=c pending=1 allow_pending_state=1 table=sup107_1_0_imagestable mbo=0x0 key=(null) ---photoLenght:90656
    Printing description of responseBinaryData:
    <OS_dispatch_data: data[0xc891b40] = { leaf, size = 90656, buf = 0x1213a000 }>
    2014-04-02 18:42:33.304 SUP102[2873:70b] -[OS_dispatch_data openForWrite:]: unrecognized selector sent to instance 0xc891b40
    2014-04-02 18:42:33.305 SUP102[2873:70b] exception: -[OS_dispatch_data openForWrite:]: unrecognized selector sent to instance 0xc891b40
    2014-04-02 18:42:33.305 SUP102[2873:70b] -[OS_dispatch_data close]: unrecognized selector sent to instance 0xc891b40
    2014-04-02 18:42:33.306 SUP102[2873:70b] [ERROR] [AppDelegate.m:497] NSInvalidArgumentException: -[OS_dispatch_data close]: unrecognized selector sent to instance 0xc891b40

    This thread talks about uploading image to SAP from a IOS device,Sending Image to SAP via iOS Native app (SUP 2.1.3)
    Midhun VP

  • How to get images dynamically from database without file paths in the table field

    I have a MS-Access database. I am working with ASP.NET. In the database there is product table in which I have "CodeNo" as a field which is a text field, and the product codes like "SM-R-2035". I also have another field "Image" which is also a text field and which have a file path in it corresponding to the particular product Image (e.g. Images\Products\SM-R-2035.jpg). So far every thing is ok. I have to update this site very frequently and lots of images are added each and every time. Its a tedious work to type the paths and file name every time and it also take a lot of time.
    What I am asking is : Is it possible to get images from a specific folder at runtime which is referenced by the "code no" itself and not the file path from the database. (Say at run time the "code no" is referenced from the database and the corresponding image is loaded dynamically from the specified folder). In other word I want to avoid the tedious work of typing.
    Can any one help with this issue. Any other simple suggestions are welcome.

    All you need to do is simple concatenation to obtain the path for the image file.  You didn't mention whether you are using VB.Net, C# or some other language to do your coding.
    If the code in your database is SM-R-2035, the file name is SM-R-2035.jpg and the path to the images foilder is Images\Products\SM-R-2035.jpg, Conceptually here is what you need to do:
    dim code_var
    dim path_var
    code_var = the code you obtain from your relevant field in the database
    path_var = "Images\Products\" & code_var & ".jpg"
    Now path_var is what you would call to obtain the image from your images folder.

  • How do I get images to automatically center in a picture box?

    How do I get images to automatically center in a picture box (e.g. place a picture box on a master page and set it so that any image placed inside will automatically center, but not scale)? This was a simple procedure in CS5 (set "Fitting Options" to 'center' by clicking on the center box in the 9-box centering tool) but seems to have disappeared in CS6/CC. Am I missing something?

    Hi and thanks. Actually, my problem is with setting the properties of the image frame to 'align center' before an image is placed, allowing me to place large numbers of images and having them automatically center instead of me centering each one manually. Even when I create an object style the frame will not hold any alignment settings and apply them to the image being placed (unless some manner of scaling has been chosen, which is not something I want). There are work-arounds I have used but it would be nice to be able to just put a picture box on a master page, set it to align it's contents to the center and just be done with it . Thanks though.

  • Getting Images To Load On Web?

    Hi all,
    I have a question about how to get images to load in an applet once it is uploaded to a website. When I run the applet in JGrasp it works fine but if I try to open the applet in a web browser (via an html file on the hard drive) nothing loads. If I take the code out that sets the background image the application loads fine in the web browser.
    The image is in the same directory as the class file and html file. Is there a way I can get this method to work (loading off the hard drive and also off the website when it's uploaded) or do I have to use a jar file? I have spent some time searching for tutorials and demos but haven't been able to get the jar file to work either. I'm fairly new to programming and most of the examples I found were way over my head.
    Any help in getting this problem solved will be greatly appreciated.
    Here is a short sample program to illustrate the problem: For some reason this sample program only loads in IE and not in Firefox.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    public class Test extends JApplet implements ActionListener
    {     Container     mainWindow;
         public void init()
         {     ImagePanel panel = new ImagePanel(new ImageIcon("Background.jpg").getImage());
              setContentPane(panel);
              mainWindow = getContentPane();
              mainWindow.setLayout(new BorderLayout());
              JLabel label = new JLabel("TESTING");
              mainWindow.add(label, BorderLayout.CENTER);
              setSize(1000, 500);
              setVisible(true);
              mainWindow.validate();
         public void actionPerformed(ActionEvent e) { }
    class ImagePanel extends JPanel
    {     private Image img;
         public ImagePanel(String img)
         {     this(new ImageIcon(img).getImage());
         public ImagePanel(Image img)
         {     this.img = img;
              Dimension size = new Dimension(img.getWidth(null), img.getHeight(null));
              setPreferredSize(size);
              setMinimumSize(size);
              setMaximumSize(size);
              setSize(size);
              setLayout(null);
         public void paintComponent(Graphics g)
         {     g.drawImage(img, 0, 0, null);
    CODE FOR HTML FILE:
    <html><body>
    <CENTER>
         <applet code="Test.class" width="1000" height="500"></applet>
    </CENTER>=
    </body></html>

    Hello again,
    I've got one more small question. I modified the code a little bit so I could create an Image folder (package) which holds all of the images and the ImagePanel class. Since the ImagePanel and images are all in the same folder, I modified the ImagePanel constructor to take a string and then load the file with that name. It works in JGrasp and when I open it in a web browser from my computer, but when I upload it to the site it no longer works. Is there a way to get at these images inside the folder when it's online without drastically changing the method I used in the first place? I saved the original files that I can go back to so if it's not an easy fix then that's no big deal, but I thought I'd ask just in case it is something simple as it would be nice to have the files more organized. Thanks.
    Here's the updated code.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import java.net.*;
    public class Test extends JApplet implements ActionListener
    {     Container     mainWindow;
         URL               url;
         public void init()
              ImagePanel panel = new ImagePanel("Background.jpg");          // background image
              setContentPane(panel);
                mainWindow = getContentPane();
                mainWindow.setLayout(new BorderLayout());
              JLabel label = new JLabel("TESTING");
              mainWindow.add(label, BorderLayout.CENTER);
              setSize(1000, 500);
              setVisible(true);
              mainWindow.validate();
         public void actionPerformed(ActionEvent e) { }
    class ImagePanel extends JPanel
    {     private Image img;
         public ImagePanel(String img)
         {     this(new ImageIcon(img).getImage());
         public ImagePanel(Image img)
         {     this.img = img;
              Dimension size = new Dimension(img.getWidth(null), img.getHeight(null));
              setPreferredSize(size);
              setMinimumSize(size);
              setMaximumSize(size);
              setSize(size);
              setLayout(null);
         public void paintComponent(Graphics g)
         {     g.drawImage(img, 0, 0, null);
    }Inside "Image" folder:
    package Image;
    import java.awt.*;
    import javax.swing.*;
    public class ImagePanel extends JPanel
         public Image img;
         public ImagePanel(String imageFile)
              Image img = new ImageIcon(getClass().getResource(imageFile)).getImage();
              this.img = img;
              Dimension size = new Dimension(img.getWidth(null), img.getHeight(null));          // set size = size of image
              setPreferredSize(size);
              setMinimumSize(size);
              setMaximumSize(size);
              setSize(size);
              setLayout(null);
         public void paintComponent(Graphics g)
              g.drawImage(img, 0, 0, null);
    }

Maybe you are looking for