Михаиллл
МихаилллJuly 14, 2019, 9:08 a.m.

Работа в QML c камерой

Добрый день.
Могу отображать увртинку с камеры на экране.
Но картинка не поворачивается при повороте телефона. Скажите пожалуйста, как ее поворачивать вместе с телефоном.
Также пытаюсь сделать фото при нажатии на единственную кнопку и отобразить это фото на картинке, но не могу сделать это.
Помогите пожалуйста.
Ниже мой код.
qml

import QtQuick 2.12
import QtMultimedia 5.12

Camera1Form {
    buttonPhoto.onClicked: //photo
    {
        imageForPhoto.source= camera
    }
}

ui.qml

import QtQuick 2.12
import QtQuick.Controls 2.12
import QtMultimedia 5.12

Item {
    width: 400
    height: 700
    property alias buttonPhoto: buttonPhoto
    property alias imageForPhoto: imageForPhoto
    property alias photoPreview: photoPreview
    property alias camera: camera

    Camera {
        id: camera

        imageProcessing.whiteBalanceMode: CameraImageProcessing.WhiteBalanceFlash

        exposure {
            exposureCompensation: -1.0
            exposureMode: Camera.ExposurePortrait
        }

        flash.mode: Camera.FlashRedEyeReduction

        imageCapture {
            onImageCaptured: {
                photoPreview.source = preview  // Show the preview in an Image
            }
        }
    }

    VideoOutput {
        anchors.bottomMargin: 300
        source: camera
        anchors.fill: parent
        focus : visible // to receive focus and capture key events when visible
    }

    Image {
        id: photoPreview
    }

    Image {
        id: imageForPhoto
        x: 21
        y: 433
        width: 219
        height: 215
        fillMode: Image.PreserveAspectFit
        source: "qrc:/qtquickplugin/images/template_image.png"

    }

    Button {
        id: buttonPhoto
        x: 264
        y: 507
        text: qsTr("Photo")
    }
}

We recommend hosting TIMEWEB
We recommend hosting TIMEWEB
Stable hosting, on which the social network EVILEG is located. For projects on Django we recommend VDS hosting.

Do you like it? Share on social networks!

3
Михаиллл
  • July 15, 2019, 9:33 a.m.

Нашел тут код, и в нем сохранение фото выполняет ,похоже, функция

    function addPicture(source) {
        var image = {
            "id": source,
            "source": source
        };
        picturesModel.push(image);
        root.picturesModelChanged();
    }

не могли бы вы помочь мне используя этот код доделать фуункцию фотографирования
Вот весь код:

import QtQuick 2.11
import QtQuick.Controls 2.4
import QtMultimedia 5.9
import QtQuick.Layouts 1.3
import QtQuick.Controls 1.4 as C1
import QtQuick.Controls.Material 2.2

ApplicationWindow {
    id: root
    visible: true
    width: 640
    height: 480
    title: "Tutorial de Cámara"

    Material.theme: Material.Dark
    Material.accent: Material.Green

    property bool rounded: roundedSwitch.position === 1.0
    property bool adapt: true
    property var picturesModel: []
    property string cameraState: turnOnSwitch.position === 1.0 ? "CameraEnabled" : "CameraDisabled"

    SoundEffect {
        id: buttonSound
        source: "qrc:/button.wav"
    }

    SoundEffect {
        id: captureSound
        source: "qrc:/cameraappCapture1.wav"
    }

    SoundEffect {
        id: beepSound
        source: "qrc:/beep.wav"
    }

    function addPicture(source) {
        var image = {
            "id": source,
            "source": source
        };
        picturesModel.push(image);
        root.picturesModelChanged();
    }

    Camera {
        id: camera
        digitalZoom: zoomSlider.value
        imageProcessing.whiteBalanceMode: CameraImageProcessing.WhiteBalanceFlash
        exposure.exposureCompensation: -1.0
        exposure.exposureMode: Camera.ExposurePortrait
        flash.mode: Camera.FlashRedEyeReduction
        imageCapture.onImageCaptured: {
            addPicture(preview);
        }
    }

    C1.SplitView {
        anchors.fill: parent
        orientation: Qt.Horizontal

        Item {
            id: cameraControls
            width: 200
            height: parent.height

            GroupBox {
                id: controls

                label: Label {
                    text: "CONTROLES"
                    font.pointSize: 15
                    font.bold: true
                }

                width: parent.width
                height: parent.height / 2

                Column {
                    anchors.fill: parent
                    spacing: 1

                    Switch {
                        id: turnOnSwitch
                        text: "ENCENDER"
                        position: 0.0
                        onPositionChanged: {
                            buttonSound.play();
                            if (position === 1.0) {
                                camera.start();
                            } else {
                                camera.stop();
                            }
                        }
                    }

                    Switch {
                        id: roundedSwitch
                        text: "CIRCULAR"
                        position: 0.0
                        onPositionChanged: {
                            buttonSound.play();
                        }
                    }

                    Image {
                        source: "qrc:/save.png"
                        sourceSize.width: 55
                        sourceSize.height: 55
                        fillMode: Image.PreserveAspectCrop
                        width: 55
                        height: 55
                        MouseArea {
                            anchors.fill: parent
                            onClicked: {
                                beepSound.play();
                                MyImageSaver.writePictures();
                            }
                        }
                    }
                }
            }
            VideoOutput {
                anchors.left: parent.left
                anchors.right: parent.right
                anchors.top: controls.bottom
                height: parent.height / 2 - 50
                source: camera
                focus: visible

                Rectangle {
                    id: captureButton1
                    width: 55
                    height: 55
                    radius: 50
                    color: "red"
                    border.width: 2
                    border.color: "lime"
                    opacity: 0.6
                    anchors.horizontalCenter: parent.horizontalCenter
                    anchors.bottom: parent.bottom
                    MouseArea {
                        anchors.fill: parent
                        onPressed: {
                            captureButton1.color = "lime";
                            camera.imageCapture.capture();
                            captureSound.play();
                        }
                        onReleased: {
                            captureButton1.color = "red";
                        }
                    }
                }

                Rectangle {
                    anchors.fill: parent
                    color: "black"
                    visible: cameraState === "CameraDisabled"
                    Image {
                        source: "qrc:/disabled.png"
                        sourceSize.width: parent.width / 2
                        sourceSize.height: parent.height / 2
                        width: parent.width / 2
                        height: parent.height / 2
                        fillMode: Image.PreserveAspectFit
                        anchors.centerIn: parent
                    }
                }
            }
            Slider {
                id: zoomSlider
                orientation: Qt.Horizontal
                from: 0
                to: camera.maximumDigitalZoom
                stepSize: camera.maximumDigitalZoom / 10
                value: 1.0
                anchors.left: parent.left
                anchors.right: parent.right
                anchors.bottom: parent.bottom
            }
        }

        Item {
            id: pictures
            height: parent.height
            Rectangle {
                anchors.fill: parent
                color: "gray"
                GridView {
                    id: grid
                    anchors.fill: parent
                    cellWidth: parent.width / 5
                    cellHeight: parent.height / 5
                    model: picturesModel
                    delegate: Rectangle {
                        property bool showPicture: true

                        id: rect
                        width: grid.cellWidth
                        height: grid.cellHeight
                        color: showPicture ? "transparent" : "white"
                        radius: rounded ? 200 : 0

                        Text {
                            anchors.centerIn: parent
                            visible: !rect.showPicture
                            font.pointSize: 60
                            text: {
                                var txt = modelData.id;
                                txt = txt.substring(txt.indexOf("_") + 1);
                                return txt;
                            }
                        }

                        Image {
                            id: image
                            visible: rect.showPicture
                            anchors.centerIn: parent
                            source: modelData.source
                            sourceSize.width: 512
                            sourceSize.height: 512
                            width: parent.width * 0.95
                            height: parent.height * 0.95
                            fillMode: Image.PreserveAspectCrop

                            layer.enabled: rounded
                            layer.effect: ShaderEffect {
                                property real adjustX: adapt ? Math.max(width/height, 1) : 1
                                property real adjustY: adapt ? Math.max(1/(width/height), 1) : 1
                                fragmentShader: "
                                        #ifdef GL_ES
                                            precision lowp float;
                                        #endif // GL_ES
                                        varying highp vec2 qt_TexCoord0;
                                        uniform highp float qt_Opacity;
                                        uniform lowp sampler2D source;
                                        uniform lowp float adjustX;
                                        uniform lowp float adjustY;

                                        void main(void) {
                                            lowp float x, y;
                                            x = (qt_TexCoord0.x - 0.5) * adjustX;
                                            y = (qt_TexCoord0.y - 0.5) * adjustY;
                                            float delta = adjustX != 1.0 ? fwidth(y) / 2.0 : fwidth(x) / 2.0;
                                            gl_FragColor = texture2D(source, qt_TexCoord0).rgba
                                                * step(x * x + y * y, 0.25)
                                                * smoothstep((x * x + y * y), 0.25 + delta, 0.25)
                                                * qt_Opacity;
                                        }"
                            }

                            Component.onCompleted: {
                                image.grabToImage(function(result) {
                                    MyImageSaver.savePicture(modelData.id, result);
                                });
                            }
                        }
                        MouseArea {
                            anchors.fill: parent
                            hoverEnabled: true
                            onEntered: {
                                rect.showPicture = false;
                            }
                            onExited: {
                                rect.showPicture = true;
                            }
                        }
                    }
                }
            }
        }
    }
}

    Михаиллл
    • July 15, 2019, 12:02 p.m.

    Так можно сохранить картинку.
    Осталось узнать как ее сохранять в папку с программой, как зеркалить картинку и как поворачивать камеру вместе с наклоном телефона.
    Может быть вы знаете как можно что-нибудь из этого сделать?

        buttonPhoto.onClicked: //photo
        {
            camera.imageCapture.captureToLocation("C:/Users/New Owner/Pictures/IMG_00000001.jpg")
            var imageFile =camera.imageCapture.capturedImagePath
            console.log("test: " + imageFile)
        }
    
      Михаиллл
      • July 15, 2019, 12:26 p.m.
      • The answer was marked as a solution.

      Так камера показывает правильно при поворотах телефона.
      Осталось узнать как картинки сохранять в папку с программой и как их потом загружать в картинки.

          VideoOutput {
              //anchors.bottomMargin: 300
              source: camera
              anchors.fill: parent
              focus : visible // to receive focus and capture key events when visible
              autoOrientation: true
          }
      

        Comments

        Only authorized users can post comments.
        Please, Log in or Sign up
        e
        • ehot
        • April 1, 2024, 12:29 a.m.

        C++ - Тест 003. Условия и циклы

        • Result:78points,
        • Rating points2
        B

        C++ - Test 002. Constants

        • Result:16points,
        • Rating points-10
        B

        C++ - Test 001. The first program and data types

        • Result:46points,
        • Rating points-6
        Last comments
        k
        kmssrFeb. 9, 2024, 5:43 a.m.
        Qt Linux - Lesson 001. Autorun Qt application under Linux как сделать автозапуск для флэтпака, который не даёт создавать файлы в ~/.config - вот это вопрос ))
        Qt WinAPI - Lesson 007. Working with ICMP Ping in Qt Без строки #include <QRegularExpressionValidator> в заголовочном файле не работает валидатор.
        EVA
        EVADec. 25, 2023, 9:30 p.m.
        Boost - static linking in CMake project under Windows Ошибка LNK1104 часто возникает, когда компоновщик не может найти или открыть файл библиотеки. В вашем случае, это файл libboost_locale-vc142-mt-gd-x64-1_74.lib из библиотеки Boost для C+…
        J
        JonnyJoDec. 25, 2023, 7:38 p.m.
        Boost - static linking in CMake project under Windows Сделал всё по-как у вас, но выдаёт ошибку [build] LINK : fatal error LNK1104: не удается открыть файл "libboost_locale-vc142-mt-gd-x64-1_74.lib" Хоть убей, не могу понять в чём дел…
        G
        GvozdikDec. 19, 2023, 8:01 a.m.
        Qt/C++ - Lesson 056. Connecting the Boost library in Qt for MinGW and MSVC compilers Для решения твой проблемы добавь в файл .pro строчку "LIBS += -lws2_32" она решит проблему , лично мне помогло.
        Now discuss on the forum
        a
        a_vlasovApril 14, 2024, 4:41 p.m.
        Мобильное приложение на C++Qt и бэкенд к нему на Django Rest Framework Евгений, добрый день! Такой вопрос. Верно ли следующее утверждение: Любое Android-приложение, написанное на Java/Kotlin чисто теоретически (пусть и с большими трудностями) можно написать и на C+…
        Павел Дорофеев
        Павел ДорофеевApril 14, 2024, 12:35 p.m.
        QTableWidget с 2 заголовками Вот тут есть кастомный QTableView с многорядностью проект поддерживается, обращайтесь
        f
        fastrexApril 4, 2024, 2:47 p.m.
        Вернуть старое поведение QComboBox, не менять индекс при resetModel Добрый день! У нас много проектов в которых используется QComboBox, в версии 5.5.1, когда модель испускает сигнал resetModel, currentIndex не менялся. В версии 5.15 при resetModel происходит try…
        AC
        Alexandru CodreanuJan. 19, 2024, 10:57 p.m.
        QML Обнулить значения SpinBox Доброго времени суток, не могу разобраться с обнулением значение SpinBox находящего в делегате. import QtQuickimport QtQuick.ControlsWindow { width: 640 height: 480 visible: tr…

        Follow us in social networks