Reputation: 333
My qml app can capture a camera image and preview it but I need to convert the image to base64
I am compiling for MacOS using Qt6.5
. I need to convert the image to base64
so I can send the photo over tcp
.
What am I doing wrong?
import QtQuick
import QtQuick.Controls
import QtMultimedia
ApplicationWindow {
visible: true
width: 640
height: 480
title: "Convert QML Image to Base64"
Camera
{
id:camera
active: true
}
CaptureSession {
camera: camera
imageCapture : ImageCapture {
id: imageCapture
onImageCaptured: function(requestId, previewImage) {
console.log("Image captured", requestId, previewImage);
// Convert the captured image to Base64
var base64String = Qt.btoa(imageCapture)
console.log(base64String)
}
}
}
Image {
id: photoPreview
source: imageCapture.preview // always shows the last captured image
}
Button {
id: takephoto
text: "Take Photo"
onClicked: imageCapture.capture()
}
}
The console.log output is not encoded base64 image data instead its this:
UVF1aWNrSW1hZ2VDYXB0dXJlKDB4NjAwMDAyZDU0NjAwKQ==
Which decoded is:
QQuickImageCapture(0x600002d54600)
Upvotes: 0
Views: 201
Reputation: 333
It appears the only QML object capable of converting images to base64 is the canvas qml type. Unless someone wants to answer this question using c++ that would also be welcomed!!!
Here we capture an image where it gets loaded to photoPreview. When the user clicks the getBase64 button it prints out the working base64
import QtQuick
import QtQuick.Window
import QtMultimedia
import QtQuick.Controls
Window {
width: 640
height: 480
visible: true
title: qsTr("encode qml image to base64")
Rectangle
{
id: bgRect
color: "white"
anchors.fill: videoOutput
}
CaptureSession {
imageCapture : ImageCapture {
id: imageCapture
onImageCaptured: {
photoPreview.visible = true
}
}
camera: Camera {
id: camera
active: true
}
videoOutput: videoOutput
}
VideoOutput {
id: videoOutput
anchors.fill: parent
MouseArea {
anchors.fill: parent;
onClicked: imageCapture.capture();
}
}
Image {
id: photoPreview
source: imageCapture.preview // always shows the last captured image
}
Canvas {
id: canvas
anchors.fill: parent
visible: false
onPaint: {
var ctx = getContext("2d");
ctx.clearRect(0, 0, width, height);
ctx.drawImage(photoPreview, 0, 0, width, height);
var dataUrl = canvas.toDataURL("image/jpeg");
console.log(dataUrl);
}
}
Button {
id: getBase64
text: "Encode Base64"
onClicked: {
canvas.requestPaint()
photoPreview.visible = false
}
}
RoundButton {
id: capture
height: 45
width: height
text: "📷"
anchors.bottom: parent.bottom
anchors.bottomMargin: parent.height * 0.05
anchors.horizontalCenter: parent.horizontalCenter
palette.button: "white"
onClicked: imageCapture.capture()
}
}
Upvotes: 0