图片转byte


public byte[] StartBmpToPrintCode(Bitmap bitmap) {
		byte temp = 0;
		int j = 7;
		int start = 0;
		if (bitmap != null) {
			int mWidth = bitmap.getWidth();
			int mHeight = bitmap.getHeight();

			int[] mIntArray = new int[mWidth * mHeight];
			byte[] data = new byte[mWidth * mHeight];
			bitmap.getPixels(mIntArray, 0, mWidth, 0, 0, mWidth, mHeight);
			encodeYUV420SP(data, mIntArray, mWidth, mHeight);
			byte[] result = new byte[mWidth * mHeight / 8];
			for (int i = 0; i < mWidth * mHeight; i++) {
				temp = (byte) ((byte) (data[i] << j) + temp);
				j--;
				if (j < 0) {
					j = 7;
				}
				if (i % 8 == 7) {
					result[(start++)] = temp;
					temp = 0;
				}
			}
			if (j != 7) {
				result[(start++)] = temp;
			}

			int aHeight = 24 - mHeight % 24;
			int perline = mWidth / 8;
			byte[] add = new byte[aHeight * perline];
			byte[] nresult = new byte[mWidth * mHeight / 8 + aHeight * perline];
			System.arraycopy(result, 0, nresult, 0, result.length);
			System.arraycopy(add, 0, nresult, result.length, add.length);

			byte[] byteContent = new byte[(mWidth / 8 + 4) * (mHeight + aHeight)];
			byte[] bytehead = new byte[4];
			bytehead[0] = 31;
			bytehead[1] = 16;
			bytehead[2] = (byte) (mWidth / 8);
			bytehead[3] = 0;
			for (int index = 0; index < mHeight + aHeight; index++) {
				System.arraycopy(bytehead, 0, byteContent, index * (perline + 4), 4);
				System.arraycopy(nresult, index * perline, byteContent, index * (perline + 4) + 4, perline);
			}

			return byteContent;
		}
		return null;
	}

	// 图片转换成byte
	public void encodeYUV420SP(byte[] yuv420sp, int[] rgba, int width, int height) {
		int frameSize = width * height;
		int[] U = new int[frameSize];
		int[] V = new int[frameSize];
		int uvwidth = width / 2;

		int bits = 8;
		int index = 0;
		int f = 0;
		for (int j = 0; j < height; j++) {
			for (int i = 0; i < width; i++) {
				int r = (rgba[index] & 0xFF000000) >> 24;
				int g = (rgba[index] & 0xFF0000) >> 16;
				int b = (rgba[index] & 0xFF00) >> 8;

				int y = (66 * r + 129 * g + 25 * b + 128 >> 8) + 16;
				int u = (-38 * r - 74 * g + 112 * b + 128 >> 8) + 128;
				int v = (112 * r - 94 * g - 18 * b + 128 >> 8) + 128;

				byte temp = (byte) (y > 255 ? 255 : y < 0 ? 0 : y);
				yuv420sp[(index++)] = (byte) (temp > 0 ? 1 : 0);
			}
		}

		f = 0;
	}

猜你喜欢

转载自zheyiw.iteye.com/blog/2119589