图片转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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值