首次在这里提问。我目前遇到了一个问题,即将从ESP32 CAM拍摄的图片发送到我的Android Studio应用程序时出现问题。
尽管图片被接收,但它大多数时候不完整,或者像附加图片中所示,显示一些灰色区域。
我注意到可用字节从图片到图片会有所变化,所以在绝望之下,我循环输出/输入流以拍摄图片,直到可用字节超过14000。尽管有很多可用字节,但图片很多时候(虽然不总是)显示了一个大块灰色像素。
我读到过这可能是因为蓝牙套接字必须在“finally”异常中关闭,但我无法使其正常工作。
非常感谢您的帮助!
private fun tomarFoto() { //Function to take the picture by sending an OutputStream and receiving the taken picture bytes through InputStream
var bytes : ByteArray? = null
val fotoEsp : ImageView = findViewById(R.id.fotoESP)
var available = 0
if (m_bluetoothSocket != null) {
try {
CoroutineScope(IO).launch {
for (i in 0..4) {
async {
m_bluetoothSocket!!.outputStream.write("a".toByteArray())
delay(1500)
}.await()
available = m_bluetoothSocket!!.inputStream.available()
println("Available1: ${available}")
if (available > 14000) {
break
}
}
println("Available2: ${available}")
bytes = ByteArray(available)
m_bluetoothSocket!!.inputStream.read(bytes, 0, available)
val bmp = BitmapFactory.decodeByteArray(bytes, 0, available)
if (bmp != null) { //Flip image upside down
fun Bitmap.flip(x: Float, y: Float, cx: Float, cy: Float): Bitmap {
val matrix = Matrix().apply { postScale(x, y, cx, cy) }
return Bitmap.createBitmap(this, 0, 0, width, height, matrix, true)
}
val cx = bmp.width / 2f
val cy = bmp.height / 2f
val flippedBitmap = bmp.flip(1f, -1f, cx, cy)
runOnUiThread {
fotoEsp.setImageBitmap(flippedBitmap)
}
} else {
runOnUiThread {
fotoEsp.setImageBitmap(bmp)
}
}
}
} catch(e: IOException) {
Log.e("client", "Cannot read data", e)
e.printStackTrace()
}
}
}
图片显示接收到的照片中存在灰色区域:
nread
。它不会等于available
,而是小于它。var nread = m_bluetoothSocket!!.inputStream.read(bytes, 0, available)
- blackapps