c# - How to print an image with a thermal printer
问题描述
I've been following many SO answers and none of them work. This is one of them, and I think is the most promising (the original answer)
public static async Task PrintImageFilesAsync(BluetoothSocket _socket, IEnumerable<FileResult> imageFiles)
{
foreach(var file in imageFiles) {
var path = file.FullPath;
var imageFile = File.Open(path, FileMode.Open, FileAccess.ReadWrite);
Bitmap originalImage = await BitmapFactory.DecodeStreamAsync(imageFile);
var strippedImage = StripColor(originalImage); // Strips the image of ALL colour, and re-colourizes it all to black.
using (var memStream = new MemoryStream()) {
int bufferLength = (int)imageFile.Length;
byte[] buffer = new byte[bufferLength];
await strippedImage.CompressAsync(Bitmap.CompressFormat.Jpeg, 0, memStream); // Writes image data to memStream
buffer = memStream.ToArray(); // Writes data in memStream to buffer
await imageFile.ReadAsync(buffer, 0, bufferLength); // Modifies the buffer IN PLACE
try
{
await _socket.OutputStream.WriteAsync(buffer, 0, bufferLength); // This part is responsible for printing.
}
catch (Java.IO.IOException ioEx)
{
originalImage.Dispose();
strippedImage.Dispose();
memStream.Close();
memStream.Dispose();
_socket.Close();
_socket.Dispose();
CrossToastPopUp.Current.ShowToastError($"{ioEx.Message}\nError: {ioEx}");
return;
}
strippedImage.Dispose();
originalImage.Dispose();
}
var status = "Print job completed.";
Debug.WriteLine(status);
CrossToastPopUp.Current.ShowToastMessage(status);
}
_socket.Close();
_socket.Dispose();
}
The function then strips the image of all color with StripColor
private static Task<Bitmap> StripColor(Bitmap image)
{
image = image.Copy(Bitmap.Config.Argb8888, true);
try
{
image.EraseColor(0);
}
catch (Java.Lang.IllegalStateException isEx)
{
Debug.WriteLine($"ERROR:\n\n{isEx.Message}");
return null;
}
return image;
}
With the current code this is the output when I print an image: https://imgur.com/a/wW4be9x
It just prints out random gibberish. Is there a way to fix this?
解决方案
推荐阅读
- android - 如何为 Agora 1 对 1 视频通话应用显示来电通知
- vue.js - allowedDate 不能用于 vuetify 上的异步或 ajax 吗?
- java - 如何在 Java 中将“2019-10-11T04:56:06.000Z”转换为时间戳?
- javascript - 在 React Native 中创建一个简单的主题标签格式化程序
- android - ScrollView、ListView、RecyclerView 和 WebView 有什么区别?
- spring-boot - Apache Ignite:JVM 暂停时间可能过长:714 毫秒
- python - I am trying to add a PYTHONPATH to environment variable on the terminal. But several ways won't work for me
- jquery - How to Separate each Card from simultaneously flipping back together
- java - 如何在java中打印从1到100的两位数?
- ios - 来自 Amazon SNS 的 VoIP 推送