2013-11-27 71 views
0

我使用以下代碼大小調整鳥圖像:重新縮放圖像在J2ME

私人圖片resizeImage(圖像SRC){

int srcWidth = src.getWidth(); 

    int srcHeight = src.getHeight(); 

    int screenWidth=getWidth()/3; 

    int screenHeight=getHeight()/3; 

    Image tmp = Image.createImage(screenWidth, srcHeight); 

    Graphics g = tmp.getGraphics(); 

    int ratio = (srcWidth << 16)/screenWidth; 

    int pos = ratio/2; 

    //Horizontal Resize   

    for (int x = 0; x < screenWidth; x++) { 
     g.setClip(x, 0, 1, srcHeight); 
     g.drawImage(src, x - (pos >> 16), 0, Graphics.LEFT | Graphics.TOP); 
     pos += ratio; 
    } 

    Image resizedImage = Image.createImage(screenWidth, screenHeight); 
    g = resizedImage.getGraphics(); 
    ratio = (srcHeight << 16)/screenHeight; 
    pos = ratio/2;   

    //Vertical resize 

    for (int y = 0; y < screenHeight; y++) { 
     g.setClip(0, y, screenWidth, 1); 
     g.drawImage(tmp, 0, y - (pos >> 16), Graphics.LEFT | Graphics.TOP); 
     pos += ratio; 
    } 
    return resizedImage; 

enter image description here }

的圖像被調整大小,但它具有白色背景,如圖所示。如何獲得只有透明背景調整大小的圖像..?

回答

0

這是我一直在使用的圖像縮放功能。包括透明度。這裏找到:http://willperone.net/Code/codescaling.php

public Image scale(Image original, int newWidth, int newHeight) { 

int[] rawInput = new int[original.getHeight() * original.getWidth()]; 
original.getRGB(rawInput, 0, original.getWidth(), 0, 0, original.getWidth(), original.getHeight()); 

int[] rawOutput = new int[newWidth * newHeight]; 

// YD compensates for the x loop by subtracting the width back out 
int YD = (original.getHeight()/newHeight) * original.getWidth() - original.getWidth(); 
int YR = original.getHeight() % newHeight; 
int XD = original.getWidth()/newWidth; 
int XR = original.getWidth() % newWidth; 
int outOffset = 0; 
int inOffset = 0; 

for (int y = newHeight, YE = 0; y > 0; y--) { 
    for (int x = newWidth, XE = 0; x > 0; x--) { 
    rawOutput[outOffset++] = rawInput[inOffset]; 
    inOffset += XD; 
    XE += XR; 
    if (XE >= newWidth) { 
     XE -= newWidth; 
     inOffset++; 
    } 
    } 
    inOffset += YD; 
    YE += YR; 
    if (YE >= newHeight) { 
    YE -= newHeight; 
    inOffset += original.getWidth(); 
    } 
} 
rawInput = null; 
return Image.createRGBImage(rawOutput, newWidth, newHeight, true); 

}

+0

感謝烏拉圭回合的答覆..我嘗試這個方法。現在我可以看到黑色像素,而不是白色像素作爲背景。它不是透明的。 – Andy

+0

這很奇怪。我已經成功地將它用於我們的最新遊戲piratediamonds.com,它們都帶有8位和24位PNG文件。請記住將「true」作爲返回Image.createRGBImage方法中的最後一個參數。 –

+0

現在它的工作..但在設備上它需要時間來調整大小。任何算法,使其更快? – Andy