Open camera inside a div [Ionic]

Asked

Viewed 984 times

4

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

  • How are you making the call to camera hj?

  • I think what you are looking for is this plugin here https://github.com/hifenhur/cordova-plugin-preview-camera this link above is from my own repository, I made some changes, but if you want to download direct from the developer repository is this one: https://github.com/cordova-plugin-camera-preview/cordova-plugin-camera-preview

1 answer

2

Look, I’m not going to give 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 am using 3 plugins Cordova: $cordovaCamera, $cordovaFile, $cordovaFileTransfer, $cordovaDevice

Install them, in the Cordova documentation has explanation: https://cordova.apache.org/plugins/

At the start of the View Controller, delcare:

 $scope.image = null;

Before changing Stage after sending, 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 one here is all image uploading operation, open the camera, all:

 //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.');
            });
        }

The PHP of sending:

  <?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 for me it works well.

It was based on this article here: https://devdactic.com/ionic-image-upload-php/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.