Bitmapfactory.decodestream возвращает NULL при печати изображения из Android PrintserviceAndroid

Форум для тех, кто программирует под Android
Ответить
Anonymous
 Bitmapfactory.decodestream возвращает NULL при печати изображения из Android Printservice

Сообщение Anonymous »

Я разрабатываю пользовательскую 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) {
CoroutineScope(Dispatchers.Main).launch {
printJob.start()
}

val fileDescriptor = printJob.document.getData()
val contentType = printJob.document.info.contentType

if (fileDescriptor == null) {
CoroutineScope(Dispatchers.Main).launch {
printJob.fail("No document data found.")
}
return
}

CoroutineScope(Dispatchers.IO).launch {
val outputStream = connectToPrinter()
if (outputStream == null) {
withContext(Dispatchers.Main) {
printJob.fail("Could not connect to printer.")
}
appLogWrite(this@MyPrintService, "Could not connect to printer.")
return@launch
}

try {
when (contentType) {
PrintDocumentInfo.CONTENT_TYPE_DOCUMENT -> handlePdfDocument(
fileDescriptor,
outputStream,
printJob
)

PrintDocumentInfo.CONTENT_TYPE_PHOTO -> handleImageDocument(
fileDescriptor,
outputStream,
printJob
)

else -> withContext(Dispatchers.Main) {
printJob.fail("Unsupported document type.")
}
}
} finally {
closeBluetoothConnection()
}
}
}

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
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Android»