Open camera inside a div [Ionic]

4

I'm developing a small application with Ionic, which will be builded for android. I need to access the camera from the device in the video application, but when I do, the camera application is opened from the outside. I would like the image from the camera to be, in real time, inside a div (or something similar) positioned inside the page. How can I do it?

    
asked by anonymous 07.10.2015 / 21:53

1 answer

2

Look, I'm not going to give you a very detailed answer, just what I use. I believe there are better solutions.

In my View, I put the following:

   <img ng-src="{{pathForImage(image)}}" style="width: 100%; height: auto;">

                <button class="button button-full button-assertive" ng-click="loadImage()">
                    FOTO DE CAPA
                </button>

                <center>
                    <h5 style="white-space:normal; color:#D95B43;">Escolha ou tire uma foto de capa de seu produto em oferta.</h5>
                    <h5>Esta será a foto destaque de seu produto.</h5>
                    <p style="white-space:normal;"><i>Visite nosso site e veja dicas de como tirar e tratar suas fotos para que sejam mais atraentes e aumentem suas vendas.</i></p>
                </center>

I'm using 3 cordova plugins: $ cordovaCamera, $ cordovaFile, $ cordovaFileTransfer, $ cordovaDevice

Install them, the Cordova documentation has an explanation: link

At the beginning of the View Controller, delcare:

 $scope.image = null;

Before changing Stage after submission, put:

  var url_img = "http://vovocooks.com.br/admin/vovos/_lib/file/img/upload.php";

            // File for Upload
            var targetPath = $scope.pathForImage($scope.image);

            // File name only
            var filename = $scope.image;;

            var options = {
                fileKey: "file",
                fileName: filename,
                chunkedMode: false,
                mimeType: "multipart/form-data",
                params: {
                    'fileName': filename
                }
            };

            $cordovaFileTransfer.upload(url_img, targetPath, options).then(function (result) {

                $ionicHistory.nextViewOptions({
                    disableBack: false,
                    historyRoot: true
                });

                $ionicHistory.clearCache();
                $ionicHistory.clearHistory();

                $scope.showAlert('Sucesso', 'Imagem e dados cadastrados.');


                $state.go('nhaac.vovoDashboard');
                 $scope.getproducts();


            });

This is the whole operation of sending the image, open the camera, everything:

 //COMEÇA A PUTARIA DAS FOTOS AQUI

        // Present Actionsheet for switch beteen Camera / Library
        $scope.loadImage = function () {
            var options = {
                title: 'Qual recurso deseja para a imagem?',
                buttonLabels: ['Ler de sua Galeria de Imagens', 'Usar a Câmera - posicione horizontalmente o celular ao tirar a foto'],
                addCancelButtonWithLabel: 'Cancelar',
                androidEnableCancelButton: true,
            };
            $cordovaActionSheet.show(options).then(function (btnIndex) {
                var type = null;
                if (btnIndex === 1) {
                    type = Camera.PictureSourceType.PHOTOLIBRARY;
                } else if (btnIndex === 2) {
                    type = Camera.PictureSourceType.CAMERA;
                }
                if (type !== null) {
                    $scope.selectPicture(type);
                }
            });
        };


        // Take image with the camera or from library and store it inside the app folder
        // Image will not be saved to users Library.
        $scope.selectPicture = function (sourceType) {
            var options = {
                quality: 100,
                destinationType: Camera.DestinationType.FILE_URI,
                sourceType: sourceType,
                saveToPhotoAlbum: false
            };

            $cordovaCamera.getPicture(options).then(function (imagePath) {
                    // Grab the file name of the photo in the temporary directory
                    var currentName = imagePath.replace(/^.*[\\/]/, '');

                    //Create a new name for the photo
                    var d = new Date(),
                        n = d.getTime(),
                        newFileName = n + ".jpg";

                    // If you are trying to load image from the gallery on Android we need special treatment!
                    if ($cordovaDevice.getPlatform() == 'Android' && sourceType === Camera.PictureSourceType.PHOTOLIBRARY) {
                        window.FilePath.resolveNativePath(imagePath, function (entry) {
                            window.resolveLocalFileSystemURL(entry, success, fail);

                            function fail(e) {
                                console.error('Error: ', e);
                            }

                            function success(fileEntry) {
                                var namePath = fileEntry.nativeURL.substr(0, fileEntry.nativeURL.lastIndexOf('/') + 1);
                                // Only copy because of access rights
                                $cordovaFile.copyFile(namePath, fileEntry.name, cordova.file.dataDirectory, newFileName).then(function (success) {
                                    $scope.image = newFileName;
                                }, function (error) {
                                    $scope.showAlert('Error', error.exception);
                                });
                            };
                        });
                    } else {
                        var namePath = imagePath.substr(0, imagePath.lastIndexOf('/') + 1);
                        // Move the file to permanent storage
                        $cordovaFile.moveFile(namePath, currentName, cordova.file.dataDirectory, newFileName).then(function (success) {
                            $scope.image = newFileName;
                        }, function (error) {
                            $scope.showAlert('Error', error.exception);
                        });
                    }
                },
                function (err) {
                    // Not always an error, maybe cancel was pressed...
                })
        };


        // Returns the local path inside the app for an image
        $scope.pathForImage = function (image) {
            if (image === null) {
                return '';
            } else {
                return cordova.file.dataDirectory + image;
            }
        };


        $scope.uploadImage = function () {
            // Destination URL
            var url = "http://vovocooks.com.br/admin/vovos/_lib/file/img/upload.php";

            // File for Upload
            var targetPath = $scope.pathForImage($scope.image);

            // File name only
            var filename = $scope.image;;

            var options = {
                fileKey: "file",
                fileName: filename,
                chunkedMode: false,
                mimeType: "multipart/form-data",
                params: {
                    'fileName': filename
                }
            };

            $cordovaFileTransfer.upload(url, targetPath, options).then(function (result) {
                $scope.showAlert('Success', 'Image upload finished.');
            });
        }

Uploading PHP:

  <?php
header('Access-Control-Allow-Origin: *');

// ESTE ARQUIVO DEVE ESTAR EM admin/vovos/_lib/file/img E SETADO EM CADASTRPDELICIAS_CONTROLLER
$target_path = "app_img/";

$target_path = $target_path . basename( $_FILES['file']['name']);

if(move_uploaded_file($_FILES['file']['tmp_name'], $target_path)) {
    echo "Upload and move success";
} else{
echo $target_path;
    echo "There was an error uploading the file, please try again!";
}
?>

Here it works for me.

Based on this article here: link

    
21.04.2017 / 18:22