2009-06-25 9 views
2

J'ai du mal à comprendre comment afficher une image (ou ImageIcon) dans une applet Java. Voici mon code. L'image (test.bmp) existe et se trouve sur le lecteur D mais quand je cours cela, j'obtiens la fenêtre de l'applet avec rien dedans. Quelqu'un peut-il me dire ce qui me manque pour faire le show ImageIcon?Comment puis-je afficher une image bitmap dans une applet Java?

public class Form1 extends JApplet { 
    ImageIcon i; 

    public void init(){ 
     i = new ImageIcon("D:\test.bmp"); 
    } 

    public void paint(Graphics g){ 
     i.paintIcon(this, g, 0, 0); 
    } 
} 

Merci, Steve.

Répondre

7

Référencer votre image à travers une absolue locale chemin d'accès au fichier peut ne pas fonctionner lorsque vous exécutez votre applet à partir d'un serveur. Utilisez le constructeur ImageIcon (emplacement d'URL) et Faites pointer l'URL vers la ressource d'image sur le serveur. Utilisez le JApplet.getCodeBase() pour déterminer l'origine de votre applet et y ajouter le nom du fichier.

public class Form1 extends JApplet { 
    Image i; 

    public void init() { 
     try { 
      i = ImageIO.read(new URL(getCodeBase(), "test.bmp")); 
     } catch (MalformedURLException ex) { 
      ex.printStackTrace(); 
     } catch (IOException ex) { 
      ex.printStackTrace(); 
     } 
    } 

    public void paint(Graphics g) { 
     g.drawImage(i, 0, 0, null); 
    } 
} 

Edit: ImageIO prend en charge BMP et l'échantillon changé fonctionne pour moi.

Edit 2: Si ça ne marche toujours pas afficher l'image, essayez « ../test.bmp » parce que lorsque vous exécutez une applet permet de dire Eclipse il a le répertoire bin comme base de code.

Édition 3: Si vous mettez votre test.bmp dans le pot ou sur le chemin de classe, vous pouvez le charger à l'aide de la même manière, mais en remplaçant

new URL(getCodeBase(), "test.bmp") 

avec

Form1.class.getResource("test.bmp") 
5

Pour commencer, c'est probablement une bonne idée d'échapper correctement votre \ as \\. Edité pour ajouter: Vous voudrez probablement apprendre l'équivalent de Path.combine (ou File.join) de votre langue (ou bibliothèque) qui est une méthode pour prendre une liste de parties de chemin de fichier et les combiner avec la plate-forme appropriée séparateur de chemin. Ou vous pouvez l'écrire vous-même rapidement en Java, car le séparateur de chemin est documenté dans File.pathSeparator.

(Du haut de ma tête, je ne savais pas que la barre oblique fonctionne toujours dans ImageIcon, mais notez l'autre réponse qui l'indique).

De plus, assurez-vous de charger un type de fichier pris en charge, tel que .png, .gif ou .jpg. BMP peut être pris en charge dans JDK 1.5

En outre, si vous exécutez dans un contexte Applet, vous pouvez ne pas avoir accès au chemin en question en raison de règles de sandboxing. Dans ce cas, rendez-le disponible dans le même chemin que le fichier HTML hébergeant l'applet (éventuellement dans le chemin du Jar, si ma mémoire est bonne), et utilisez un chemin relatif.

+0

Je pense que nous avons un gagnant. S'il avait nommé son fichier "imagetest.bmp", le problème aurait été évident. –

+1

+1 c'est probablement le problème. La seule raison pour laquelle vous n'obtenez pas d'erreur de compilation est que "\ t" est une séquence d'échappement valide pour le caractère de tabulation. –

+0

Ce qui nous amène à la deuxième leçon: Vérifiez si init (ouverture du fichier) a réussi. – schnaader

0

De l'Java Docs:

Lorsque vous spécifiez un chemin, utilisez la barre oblique standard Internet ("/") comme séparateur

1

Au lieu de faire un ImageIcon qui est dit de se dessiner sur un graphique, essayez de cette façon:

public class Form1 extends JApplet { 
    Image i; 

    public void init(){ 
     i = getImage("D:\\test.bmp"); 
    } 

    public void paint(Graphics g){ 
     g.drawImage(i,0,0,this); 
    } 
} 

En outre, vous pouvez essayer d'utiliser .png au lieu d'un fichier .bmp.

0

Les fichiers bmp ne sont pas supprimés dans Java.

Vous devriez probablement envisager unsing d'autres formats tels que .png, Si vous avez vraiment AVEZ de le faire .gif ou .jpg

, est ici un article de Java du monde qui explique comment lire le fichier de carte de bits et l'interpréter.

Java Tip 43: How to read 8- and 24-bit Microsoft Windows bitmaps in Java applications de JavaWorld

Je ne l'ai jamais essayé si

+2

BMP n'est pas pris en charge dans Swing/ImageIcon. ImageIO est cependant heureux de le lire (ref: http://forums.sun.com/thread.jspa?threadID=666189) – akarnokd

1

ImageJ est une application Open Source/bibliothèque qui supporte les formats peuvent y compris BMP.

Voici un code réel à l'aide de BMPDecoder ImageJ:

Voici le license statement.

import java.awt.image.ColorModel; 
import java.awt.image.IndexColorModel; 
import java.awt.image.MemoryImageSource; 
import java.io.IOException; 
import java.io.InputStream; 

import javax.swing.ImageIcon; 
import javax.swing.JFrame; 
import javax.swing.JLabel; 

public class BMPDecoder { 
    InputStream is; 
    int curPos = 0; 

    int bitmapOffset; // starting position of image data 

    int width; // image width in pixels 
    int height; // image height in pixels 
    short bitsPerPixel; // 1, 4, 8, or 24 (no color map) 
    int compression; // 0 (none), 1 (8-bit RLE), or 2 (4-bit RLE) 
    int actualSizeOfBitmap; 
    int scanLineSize; 
    int actualColorsUsed; 

    byte r[], g[], b[]; // color palette 
    int noOfEntries; 

    byte[] byteData; // Unpacked data 
    int[] intData; // Unpacked data 
    boolean topDown; 

    private int readInt() throws IOException { 
     int b1 = is.read(); 
     int b2 = is.read(); 
     int b3 = is.read(); 
     int b4 = is.read(); 
     curPos += 4; 
     return ((b4 << 24) + (b3 << 16) + (b2 << 8) + (b1 << 0)); 
    } 

    private short readShort() throws IOException { 
     int b1 = is.read(); 
     int b2 = is.read(); 
     curPos += 2; 
     return (short) ((b2 << 8) + b1); 
    } 

    void getFileHeader() throws IOException, Exception { 
     // Actual contents (14 bytes): 
     short fileType = 0x4d42;// always "BM" 
     int fileSize; // size of file in bytes 
     short reserved1 = 0; // always 0 
     short reserved2 = 0; // always 0 

     fileType = readShort(); 
     if (fileType != 0x4d42) 
      throw new Exception("Not a BMP file"); // wrong file type 
     fileSize = readInt(); 
     reserved1 = readShort(); 
     reserved2 = readShort(); 
     bitmapOffset = readInt(); 
    } 

    void getBitmapHeader() throws IOException { 

     // Actual contents (40 bytes): 
     int size; // size of this header in bytes 
     short planes; // no. of color planes: always 1 
     int sizeOfBitmap; // size of bitmap in bytes (may be 0: if so, 
          // calculate) 
     int horzResolution; // horizontal resolution, pixels/meter (may be 0) 
     int vertResolution; // vertical resolution, pixels/meter (may be 0) 
     int colorsUsed; // no. of colors in palette (if 0, calculate) 
     int colorsImportant; // no. of important colors (appear first in 
           // palette) (0 means all are important) 
     int noOfPixels; 

     size = readInt(); 
     width = readInt(); 
     height = readInt(); 
     planes = readShort(); 
     bitsPerPixel = readShort(); 
     compression = readInt(); 
     sizeOfBitmap = readInt(); 
     horzResolution = readInt(); 
     vertResolution = readInt(); 
     colorsUsed = readInt(); 
     colorsImportant = readInt(); 

     topDown = (height < 0); 
     if (topDown) 
      height = -height; 
     noOfPixels = width * height; 

     // Scan line is padded with zeroes to be a multiple of four bytes 
     scanLineSize = ((width * bitsPerPixel + 31)/32) * 4; 

     actualSizeOfBitmap = scanLineSize * height; 

     if (colorsUsed != 0) 
      actualColorsUsed = colorsUsed; 
     else 
     // a value of 0 means we determine this based on the bits per pixel 
     if (bitsPerPixel < 16) 
      actualColorsUsed = 1 << bitsPerPixel; 
     else 
      actualColorsUsed = 0; // no palette 
    } 

    void getPalette() throws IOException { 
     noOfEntries = actualColorsUsed; 
     // IJ.write("noOfEntries: " + noOfEntries); 
     if (noOfEntries > 0) { 
      r = new byte[noOfEntries]; 
      g = new byte[noOfEntries]; 
      b = new byte[noOfEntries]; 

      int reserved; 
      for (int i = 0; i < noOfEntries; i++) { 
       b[i] = (byte) is.read(); 
       g[i] = (byte) is.read(); 
       r[i] = (byte) is.read(); 
       reserved = is.read(); 
       curPos += 4; 
      } 
     } 
    } 

    void unpack(byte[] rawData, int rawOffset, int bpp, byte[] byteData, 
      int byteOffset, int w) throws Exception { 
     int j = byteOffset; 
     int k = rawOffset; 
     byte mask; 
     int pixPerByte; 

     switch (bpp) { 
     case 1: 
      mask = (byte) 0x01; 
      pixPerByte = 8; 
      break; 
     case 4: 
      mask = (byte) 0x0f; 
      pixPerByte = 2; 
      break; 
     case 8: 
      mask = (byte) 0xff; 
      pixPerByte = 1; 
      break; 
     default: 
      throw new Exception("Unsupported bits-per-pixel value: " + bpp); 
     } 

     for (int i = 0;;) { 
      int shift = 8 - bpp; 
      for (int ii = 0; ii < pixPerByte; ii++) { 
       byte br = rawData[k]; 
       br >>= shift; 
       byteData[j] = (byte) (br & mask); 
       // System.out.println("Setting byteData[" + j + "]=" + 
       // Test.byteToHex(byteData[j])); 
       j++; 
       i++; 
       if (i == w) 
        return; 
       shift -= bpp; 
      } 
      k++; 
     } 
    } 

    void unpack24(byte[] rawData, int rawOffset, int[] intData, int intOffset, 
      int w) { 
     int j = intOffset; 
     int k = rawOffset; 
     int mask = 0xff; 
     for (int i = 0; i < w; i++) { 
      int b0 = (((int) (rawData[k++])) & mask); 
      int b1 = (((int) (rawData[k++])) & mask) << 8; 
      int b2 = (((int) (rawData[k++])) & mask) << 16; 
      intData[j] = 0xff000000 | b0 | b1 | b2; 
      j++; 
     } 
    } 

    void unpack32(byte[] rawData, int rawOffset, int[] intData, int intOffset, 
      int w) { 
     int j = intOffset; 
     int k = rawOffset; 
     int mask = 0xff; 
     for (int i = 0; i < w; i++) { 
      int b0 = (((int) (rawData[k++])) & mask); 
      int b1 = (((int) (rawData[k++])) & mask) << 8; 
      int b2 = (((int) (rawData[k++])) & mask) << 16; 
      int b3 = (((int) (rawData[k++])) & mask) << 24; // this gets 
                  // ignored! 
      intData[j] = 0xff000000 | b0 | b1 | b2; 
      j++; 
     } 
    } 

    void getPixelData() throws IOException, Exception { 
     byte[] rawData; // the raw unpacked data 

     // Skip to the start of the bitmap data (if we are not already there) 
     long skip = bitmapOffset - curPos; 
     if (skip > 0) { 
      is.skip(skip); 
      curPos += skip; 
     } 

     int len = scanLineSize; 
     if (bitsPerPixel > 8) 
      intData = new int[width * height]; 
     else 
      byteData = new byte[width * height]; 
     rawData = new byte[actualSizeOfBitmap]; 
     int rawOffset = 0; 
     int offset = (height - 1) * width; 
     for (int i = height - 1; i >= 0; i--) { 
      int n = is.read(rawData, rawOffset, len); 
      if (n < len) 
       throw new Exception("Scan line ended prematurely after " + n 
         + " bytes"); 
      if (bitsPerPixel == 24) 
       unpack24(rawData, rawOffset, intData, offset, width); 
      else if (bitsPerPixel == 32) 
       unpack32(rawData, rawOffset, intData, offset, width); 
      else 
       // 8-bits or less 
       unpack(rawData, rawOffset, bitsPerPixel, byteData, offset, 
         width); 
      rawOffset += len; 
      offset -= width; 
     } 
    } 

    public void read(InputStream is) throws IOException, Exception { 
     this.is = is; 
     getFileHeader(); 
     getBitmapHeader(); 
     if (compression != 0) 
      throw new Exception("Compression not supported"); 
     getPalette(); 
     getPixelData(); 
    } 

    public MemoryImageSource makeImageSource() { 
     ColorModel cm; 
     MemoryImageSource mis; 

     if (noOfEntries > 0) { 
      // There is a color palette; create an IndexColorModel 
      cm = new IndexColorModel(bitsPerPixel, noOfEntries, r, g, b); 
     } else { 
      // There is no palette; use the default RGB color model 
      cm = ColorModel.getRGBdefault(); 
     } 

     // Create MemoryImageSource 

     if (bitsPerPixel > 8) { 
      // use one int per pixel 
      mis = new MemoryImageSource(width, height, cm, intData, 0, width); 
     } else { 
      // use one byte per pixel 
      mis = new MemoryImageSource(width, height, cm, byteData, 0, width); 
     } 

     return mis; // this can be used by Component.createImage() 
    } 

    public static void main(String[] aqgs) { 
     BMPDecoder bd = new BMPDecoder(); 
     try { 
      bd.read(BMPDecoder.class.getResourceAsStream("bmp.bmp")); 
     } catch (Exception e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
     JFrame jf = new JFrame(); 
     JLabel jl = new JLabel(); 
     ImageIcon ii = new ImageIcon(jl.createImage(bd.makeImageSource())); 
     jl.setIcon(ii); 
     jf.add(jl); 
     jf.pack(); 
     jf.setVisible(true); 
    } 
} 
Questions connexes