我需要单色位图文件,其宽度可以被8整除。它是打印图像的基本要求。我得到byte []作为输入,需要创建我可以传递给打印机的位串。以下是我正在使用的代码,但它只打印垂直线。任何人都可以帮助我通过代码创建这样的单色文件
private Android.Graphics.Bitmap ConvertArgbToOneColor(Android.Graphics.Bitmap bmpOriginal, int width, int height)
{
Android.Graphics.Bitmap bwBitmap = bmpOriginal;
float[] hsv = new float[3];
for (int col = 0; col < bmpOriginal.Width; col++)
{
for (int row = 0; row < bmpOriginal.Height; row++)
{
// Android.Graphics.Color.ColorToHSV( bmpOriginal.GetPixel(col, row), hsv);
Android.Graphics.Color.ColorToHSV(Android.Graphics.Color.HSVToColor(bmpOriginal.GetPixel(col, row), hsv), hsv);
if (hsv[2] > 0.5f)
{
bwBitmap.SetPixel(col, row, Android.Graphics.Color.White);// 0xffffffff);
}
else
{
bwBitmap.SetPixel(col, row, Android.Graphics.Color.Black); // 0xff000000);
}
}
}
return bwBitmap;
}
public string GetPrintCommand(string FileName, byte[] imageBytes)
{
Android.Graphics.Bitmap bitmap = Android.Graphics.BitmapFactory.DecodeByteArray(imageBytes, 0, imageBytes.Length);
Android.Graphics.Bitmap bmpMonochrome = Android.Graphics.Bitmap.CreateBitmap(128,128, Android.Graphics.Bitmap.Config.Argb8888);
Android.Graphics.Canvas canvas = new Android.Graphics.Canvas(bmpMonochrome);
Android.Graphics.ColorMatrix ma = new Android.Graphics.ColorMatrix();
ma.SetSaturation(0);
Android.Graphics.Paint paint = new Android.Graphics.Paint();
paint.SetColorFilter(new Android.Graphics.ColorMatrixColorFilter(ma));
canvas.DrawBitmap(bitmap, 0, 0, paint);
// Convert the file with black and white format
bmpMonochrome = ConvertArgbToOneColor(bmpMonochrome, 128, 128);
//create byte array for monochrome image
ByteBuffer buffer = ByteBuffer.Allocate(bmpMonochrome.ByteCount);
bmpMonochrome.CopyPixelsToBuffer(buffer);
buffer.Rewind();
IntPtr classHandle = JNIEnv.FindClass("java/nio/ByteBuffer");
IntPtr methodId = JNIEnv.GetMethodID(classHandle, "array", "()[B");
IntPtr resultHandle = JNIEnv.CallObjectMethod(buffer.Handle, methodId);
byte[] m_imageArray = JNIEnv.GetArray<byte>(resultHandle);
string BinaryImage = "";
BinaryImage = BitConverter.ToString(m_imageArray).Replace("-", "");
string s = string.Format("~DG{0}.GRF,{1},{2},{3}", FileName, bmpMonochrome.ByteCount, bmpMonochrome.RowBytes, BinaryImage);
JNIEnv.DeleteLocalRef(resultHandle);
return s;
}