Михаиллл
Михаиллл14 июля 2019 г. 9:08

Работа в 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")
    }
}

Рекомендуем хостинг TIMEWEB
Рекомендуем хостинг TIMEWEB
Стабильный хостинг, на котором располагается социальная сеть EVILEG. Для проектов на Django рекомендуем VDS хостинг.

Вам это нравится? Поделитесь в социальных сетях!

3
Михаиллл
  • 15 июля 2019 г. 9:33

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

    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;
                            }
                        }
                    }
                }
            }
        }
    }
}

    Михаиллл
    • 15 июля 2019 г. 12:02

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

        buttonPhoto.onClicked: //photo
        {
            camera.imageCapture.captureToLocation("C:/Users/New Owner/Pictures/IMG_00000001.jpg")
            var imageFile =camera.imageCapture.capturedImagePath
            console.log("test: " + imageFile)
        }
    
      Михаиллл
      • 15 июля 2019 г. 12:26
      • Ответ был помечен как решение.

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

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

        Комментарии

        Только авторизованные пользователи могут публиковать комментарии.
        Пожалуйста, авторизуйтесь или зарегистрируйтесь
        d
        • dsfs
        • 26 апреля 2024 г. 1:56

        C++ - Тест 004. Указатели, Массивы и Циклы

        • Результат:80баллов,
        • Очки рейтинга4
        d
        • dsfs
        • 26 апреля 2024 г. 1:45

        C++ - Тест 002. Константы

        • Результат:50баллов,
        • Очки рейтинга-4
        d
        • dsfs
        • 26 апреля 2024 г. 1:35

        C++ - Тест 001. Первая программа и типы данных

        • Результат:73баллов,
        • Очки рейтинга1
        Последние комментарии
        k
        kmssr8 февраля 2024 г. 15:43
        Qt Linux - Урок 001. Автозапуск Qt приложения под Linux как сделать автозапуск для флэтпака, который не даёт создавать файлы в ~/.config - вот это вопрос ))
        АК
        Анатолий Кононенко4 февраля 2024 г. 22:50
        Qt WinAPI - Урок 007. Работаем с ICMP Ping в Qt Без строки #include <QRegularExpressionValidator> в заголовочном файле не работает валидатор.
        EVA
        EVA25 декабря 2023 г. 7:30
        Boost - статическая линковка в CMake проекте под Windows Ошибка LNK1104 часто возникает, когда компоновщик не может найти или открыть файл библиотеки. В вашем случае, это файл libboost_locale-vc142-mt-gd-x64-1_74.lib из библиотеки Boost для C+…
        J
        JonnyJo25 декабря 2023 г. 5:38
        Boost - статическая линковка в CMake проекте под Windows Сделал всё по-как у вас, но выдаёт ошибку [build] LINK : fatal error LNK1104: не удается открыть файл "libboost_locale-vc142-mt-gd-x64-1_74.lib" Хоть убей, не могу понять в чём дел…
        G
        Gvozdik18 декабря 2023 г. 18:01
        Qt/C++ - Урок 056. Подключение библиотеки Boost в Qt для компиляторов MinGW и MSVC Для решения твой проблемы добавь в файл .pro строчку "LIBS += -lws2_32" она решит проблему , лично мне помогло.
        Сейчас обсуждают на форуме
        G
        Gar22 апреля 2024 г. 2:46
        Clipboard Как скопировать окно целиком в clipb?
        DA
        Dr Gangil Academics20 апреля 2024 г. 4:45
        Unlock Your Aesthetic Potential: Explore MSC in Facial Aesthetics and Cosmetology in India Embark on a transformative journey with an msc in facial aesthetics and cosmetology in india . Delve into the intricate world of beauty and rejuvenation, guided by expert faculty and …
        a
        a_vlasov14 апреля 2024 г. 3:41
        Мобильное приложение на C++Qt и бэкенд к нему на Django Rest Framework Евгений, добрый день! Такой вопрос. Верно ли следующее утверждение: Любое Android-приложение, написанное на Java/Kotlin чисто теоретически (пусть и с большими трудностями) можно написать и на C+…
        Павел Дорофеев
        Павел Дорофеев13 апреля 2024 г. 23:35
        QTableWidget с 2 заголовками Вот тут есть кастомный QTableView с многорядностью проект поддерживается, обращайтесь
        f
        fastrex4 апреля 2024 г. 1:47
        Вернуть старое поведение QComboBox, не менять индекс при resetModel Добрый день! У нас много проектов в которых используется QComboBox, в версии 5.5.1, когда модель испускает сигнал resetModel, currentIndex не менялся. В версии 5.15 при resetModel происходит try…

        Следите за нами в социальных сетях