j2me图片缩放方法

今天在网上看到几个在j2me中实现图片缩放的函数,很不错,记录下来。

注:src为原始图片,destW为修改后的宽度,destH为修改后的高度

 

1.方法一

public static Image resizeImage(Image src, int destW, int destH) { 
 int srcW = src.getWidth(); 
 int srcH = src.getHeight(); 
 int[] destPixels = new int[destW * destH]; 
 int[] srcPixels = new int[srcW * srcH];
 	src.getRGB(srcPixels, 0, srcW, 0, 0, srcW, srcH);
 	for (int destY = 0; destY < destH; ++destY) { 
		for (int destX = 0; destX < destW; ++destX) { 
			int srcX = (destX * srcW) / destW; 
 int srcY = (destY * srcH) / destH; 
			destPixels[destX + destY * destW] = srcPixels[srcX + srcY * srcW]; 
		} 
	} 
 return Image.createRGBImage(destPixels, destW, destH, true); 
}

 

2.方法二

public static Image ZoomImage(Image src, int desW, int desH) { Image desImg = null; int srcW = src.getWidth(); // 原始图像宽  int srcH = src.getHeight(); // 原始图像高  int[] srcBuf = new int[srcW * srcH]; // 原始图片像素信息缓存 src.getRGB(srcBuf, 0, srcW, 0, 0, srcW, srcH); // 计算插值表  int[] tabY = new int[desH]; int[] tabX = new int[desW]; int sb = 0; int db = 0; int tems = 0; int temd = 0; int distance = srcH > desH ? srcH : desH; for (int i = 0; i <= distance; i++) { tabY[db] = sb; tems += srcH; temd += desH; if (tems > distance) { tems -= distance; sb++; } if (temd > distance) { temd -= distance; db++; } } sb = 0; db = 0; tems = 0; temd = 0; distance = srcW > desW ? srcW : desW; for (int i = 0; i <= distance; i++) { tabX[db] = (short) sb; tems += srcW; temd += desW; if (tems > distance) { tems -= distance; sb++; } if (temd > distance) { temd -= distance; db++; } } // 生成放大缩小后图形像素buf  int[] desBuf = new int[desW * desH]; int dx = 0; int dy = 0; int sy = 0; int oldy = -1; for (int i = 0; i < desH; i++) { if (oldy == tabY[i]) { System.arraycopy(desBuf, dy - desW, desBuf, dy, desW); } else { dx = 0; for (int j = 0; j < desW; j++) { desBuf[dy + dx] = srcBuf[sy + tabX[j]]; dx++; } sy += (tabY[i] - oldy) * srcW; } oldy = tabY[i]; dy += desW; } // 生成图片 desImg = Image.createRGBImage(desBuf, desW, desH, true); return desImg; }

 

3.方法三

public static Image scaleImage(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]; 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(); } } return Image.createRGBImage(rawOutput, newWidth, newHeight, true); }

你可能感兴趣的:(j2me图片缩放方法)