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://i.stack.imgur.com/hZjHr.jpg
It just prints out random gibberish. Is there a way to fix this?