Я разрабатываю пользовательскую printservice для приложения Android, которое подключается к тепловому принтеру Bluetooth. Мой сервис успешно обрабатывает документы PDF, преобразуя каждую страницу в растровый карту и печатая ее. Тем не менее, я сталкиваюсь с проблемой при попытке распечатать файлы изображений (printdocumentinfo.content_type_photo).
Ядро проблемы, по -видимому, заключается в том, что bitmapfactory.decodestream () возвращает null , указывая на то, что оно не может декодировать данные изображения. Я беру parcelfiledescriptor из printjob , написание его содержимого во временное файл, а затем пытаюсь расшифровать этот файл.
Что я пытаюсь сделать:
Пользователь выбирает изображение для печати. onprintJobqueud я называю функцию handleimagedocument для обработки задания. Bitmapfactory.decodestream (). < /P>
Цель состоит в том, чтобы изменить размер и распечатать этот растровый карту на подключенный принтер Bluetooth. Это происходит, даже если временный файл создается и имеет ненулевой размер, что предполагает, что данные копируются. Когда я пытаюсь открыть его с помощью просмотра изображения, он не может отображать исходное изображение. Размер файла верен, но данные, кажется, являются недействительными или неполными.// ... (imports and class definition)
override fun onPrintJobQueued(printJob: PrintJob) {
// ... (logic to get fileDescriptor and contentType)
// Call handleImageDocument
handleImageDocument(fileDescriptor, outputStream, printJob)
// ...
}
private suspend fun handleImageDocument(
fileDescriptor: ParcelFileDescriptor,
outputStream: OutputStream,
printJob: PrintJob
) {
var tempFile: File? = null
var inputStream: FileInputStream? = null
try {
// Step 1: Copy to a temp file
tempFile = File.createTempFile("temp_image", ".png", cacheDir)
ParcelFileDescriptor.AutoCloseInputStream(fileDescriptor).use { input ->
FileOutputStream(tempFile).use { output ->
input.copyTo(output)
}
}
// Step 2: Decode the bitmap from the temp file
// The issue is here: this line returns null
inputStream = withContext(Dispatchers.IO) {
FileInputStream(tempFile)
}
val bitmap = BitmapFactory.decodeStream(inputStream)
if (bitmap == null) {
withContext(Dispatchers.Main) {
printJob.fail("Failed to decode image from the temporary file.")
}
// Log message confirms this path is being taken
appLogWrite(this, "Failed to decode image. Bitmap is null.")
return
}
// ... (rest of the printing logic, which is not reached)
} catch (e: Exception) {
// ... (error handling)
} finally {
// Cleanup
try {
inputStream?.close()
// tempFile?.delete()
} catch (e: Exception) {
appLogWrite(this, "Failed to cleanup temp image file: ${e.message}")
}
}
}
Подробнее здесь: https://stackoverflow.com/questions/797 ... id-printse