2009-06-25 54 views
2

我很難搞清楚如何在Java applet中顯示Image(或ImageIcon)。以下是我的代碼。圖片(test.bmp)確實存在,並且位於D驅動器上,但是當我運行它時,我得到了沒有任何內容的小程序窗口。有人可以告訴我我失去了什麼ImageIcon秀?如何在Java applet中顯示位圖圖像?

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); 
    } 
} 

謝謝,史蒂夫。

回答

7

通過本地絕對引用您的圖像從服務器運行applet時文件路徑可能不起作用。 使用ImageIcon(URL位置)構造函數和 使URL指向服務器上的圖像資源。使用JApplet.getCodeBase()來確定applet的起源位置並將文件名附加到它。

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); 
    } 
} 

編輯: ImageIO的支持BMP和改變樣品爲我工作。

編輯2:如果仍然不顯示圖像,請嘗試「../test.bmp」,因爲當你運行一個小程序,從可以說的Eclipse它有bin目錄作爲基本代碼。

編輯3:如果你把你的測試。BMP放進瓶子裏或在classpath中,則可以使用相同的方法,但與

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

首先,將\ \正確地轉義爲\\可能是一個好主意。

修改爲添加:您可能想要了解與Path.combine(或File.join)等效的語言(或庫),這是一種獲取文件路徑部分列表的方法,並將它們與平臺相關路徑分隔符。或者你可以用Java快速編寫它,因爲路徑分隔符記錄在File.pathSeparator。 (關於我的頭頂,我不知道正斜槓總是在ImageIcon中工作,但請注意另一個表示這個的響應)。

此外,請確保您正在加載受支持的文件類型,例如.png,.gif或.jpg。 BMP可能在JDK 1.5中受支持

此外,如果您在Applet上下文中運行,由於沙箱規則,您可能無法訪問有問題的路徑。在這種情況下,請使用與託管applet的HTML文件相同的路徑(可能在Jar的路徑中,如果內存爲我服務),並使用相對路徑。

+0

我想我們有一個贏家。如果他將他的文件命名爲「imagetest.bmp」,那麼問題就很明顯了。 – 2009-06-25 17:56:43

+1

+1這可能是問題所在。您沒有收到編譯器錯誤的唯一原因是因爲「\ t」是製表符的有效轉義序列。 – 2009-06-25 17:56:56

0

Java Docs

指定路徑時,使用 Internet標準正斜槓( 「/」) 作爲分隔符

1

而不是讓被告知要自己繪製到圖形一個ImageIcon的更換

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

加載,請嘗試它這樣:

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); 
    } 
} 

此外,您可能想嘗試使用.png而不是.bmp文件。

1

ImageJ是具有5月格式,包括BMP支持開源應用程序/庫。

下面是使用BMPDecoder從ImageJ的一些實際的代碼:

這裏是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); 
    } 
}