1.将图片放到assets目录中
2.读取assetes中的图片
Bitmap getBitmap= getImageFromAssetsFile(context,name);
String data="";
if(getBitmap!=null){
data=sendPhoto(context,getBitmap);
}
3.组装打印命令
? printMessage=“打印机命令”+data
4.发送命令
com.sendHex(printMessage)
/**
* 从Assets中读取图片
*/
public static Bitmap getImageFromAssetsFile(Context context,String fileName) {
Bitmap image = null;
AssetManager am = context.getResources().getAssets();
try {
InputStream is = am.open(fileName);
image = BitmapFactory.decodeStream(is);
is.close();
} catch (IOException e) {
e.printStackTrace();
}
return image;
}
/**
* 将图片转换成十六进制字符串
* @param
* @return
*/
public static String sendPhoto(Context context,Bitmap bitmap) {
int width = bitmap.getWidth();
int height = bitmap.getHeight();
int widthByte = (width - 1) / 8 + 1;
int[] pixels = new int[width * height];
bitmap.getPixels(pixels, 0, width, 0, 0, width, height);
List<byte[]> dataList = new ArrayList<>();
///图片二值化处理
for (int y = 0; y < height; y++) {
byte[] rowData = new byte[widthByte];
byte temp = 0;
int offset;
for (int x = 0; x < width; x++) {
int pixel = pixels[width * y + x];
int alpha = pixel >> 24 & 0xFF;
int red = pixel >> 16 & 0xFF;
int green = pixel >> 8 & 0xFF;
int blue = pixel & 0xFF;
int value = alpha == 0 ? 0 : (int) ((float) red * 0.3 + (float) green * 0.59 + (float) blue * 0.11) > 127 ? 0 : 1;
offset = x % 8;
if (value == 1) {
temp |= (0x80 >> offset);
}
if (offset == 7 || x >= width - 1) {
rowData[x / 8] = temp;
temp = 0;
}
}
dataList.add(rowData);
}
String photoStr="";
StringBuilder dataGet=new StringBuilder();
for (int i = 0; i < height; i++) {
dataGet.append(byte2hex(dataList.get(i)));
}
photoStr+=photoStr+dataGet.toString();
return photoStr;
}
/**
* 转16进制字符串
* @param b
* @return
*/
public static String byte2hex(byte[] b)
{
StringBuffer sb = new StringBuffer();
String stmp = "";
for (int n = 0; n < b.length; n++) {
stmp = Integer.toHexString(b[n] & 0XFF);
if (stmp.length() == 1) {
sb.append("0" + stmp);
} else {
sb.append(stmp);
}
}
return sb.toString().toUpperCase();
}
|