locked
[WP8.1[HTML]]MediaCapture Preview element size Windows Phone 8.1 RRS feed

  • Question

  • Hi.

    I'm working on Camera for Windows Phone 8.1 using MediaCapture (WinJS). I'm able to preview the camera to a <video> element. but i'm unable to increase the size of it. The preview is so small. I'm using max resolution

    Tried using some CSS, but didn't work

    Any work around on how i can increase the size of it or show full screen?


    Thursday, July 2, 2015 12:15 PM

Answers

  • Hello Ravindra Sharma,

    I was able to reproduce the issue with sample code you provided I tested it windows phone device and the preview was seeing small as you described.

    I putted a select for resolution in your html and populated the available resolutions and set the resolution at runtime. When I changed the option in resolution I could see that the preview size was actually changing according to the resolution. So I  think the issue is with resolution please see this code.

    HTML

    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8" />
        <title>App1</title>
    
        <!-- WinJS references -->
        <!-- At runtime, ui-themed.css resolves to ui-themed.light.css or ui-themed.dark.css
        based on the user’s theme setting. This is part of the MRT resource loading functionality. -->
        <link href="/css/ui-themed.css" rel="stylesheet" />
        <script src="//Microsoft.Phone.WinJS.2.1/js/base.js"></script>
        <script src="//Microsoft.Phone.WinJS.2.1/js/ui.js"></script>
        <script src="js/wincompact.js"></script>
    
        <!-- App1 references -->
        <link href="/css/default.css" rel="stylesheet" />
        <script src="/js/default.js"></script>
        <script src="js/MobileServices.Web-1.2.7.min.js"></script>
    
        <!-- <script src="js/MobileServices.intellisense.js"></script>-->
    </head>
    <body class="phone">
        <button id="capture">Capture</button> <button id="previewbtn">Preview</button> <button id="switchcambtn">Switch</button> <button id="stopcam">Stop</button>
        <select id="selectResolutions" title="Camera Resolutions"></select>
    
    
    
        <video id="previewvid" style="float:left;"></video>
    
        <img id="img1" />
    
    
    
    </body>
    </html>
    
    

    Javascript

    var mediaCapture = new Windows.Media.Capture.MediaCapture();
    var cameraSettings;
    var allcameras = [];
    var nextcamera;
    var videodeviceid;
    var mediaType = Windows.Media.Capture.MediaStreamType
    var cameraResolutions = [];
    
    (function () {
        "use strict";
    
        var app = WinJS.Application;
        var activation = Windows.ApplicationModel.Activation;
    
        app.onactivated = function (args) {
            if (args.detail.kind === activation.ActivationKind.launch) {
                if (args.detail.previousExecutionState !== activation.ApplicationExecutionState.terminated) {
                    // TODO: This application has been newly launched. Initialize
                    // your application here.
                } else {
                    // TODO: This application has been reactivated from suspension.
                    // Restore application state here.
                }
                args.setPromise(WinJS.UI.processAll());
                var x = document.getElementById("capture");
                x.addEventListener("click", fun, false);
    
                previewbtn.addEventListener("click", preview, false);
                stopcam.addEventListener("click", stopcapture, false);
                switchcambtn.addEventListener("click", switchcam, false);
                selectResolutions.addEventListener("change", setCameraResolution);
                var deviceInfo = Windows.Devices.Enumeration.DeviceInformation;
                deviceInfo.findAllAsync(Windows.Devices.Enumeration.DeviceClass.videoCapture).done(function (devices) {
                    videodeviceid = devices[0].id; // opening rare face camera
                });
    
                init(videodeviceid);
    
    
            }
        };
    
        app.oncheckpoint = function (args) {
            // TODO: This application is about to be suspended. Save any state
            // that needs to persist across suspensions here. You might use the
            // WinJS.Application.sessionState object, which is automatically
            // saved and restored across suspension. If you need to complete an
            // asynchronous operation before your application is suspended, call
            // args.setPromise().
        };
    
    
        app.start();
    
    
    
        function init(videodeviceid) {
            cameraSettings = new Windows.Media.Capture.MediaCaptureInitializationSettings();
            cameraSettings.photoCaptureSource = Windows.Media.Capture.PhotoCaptureSource.videoPreview;
            cameraSettings.streamingCaptureMode = Windows.Media.Capture.StreamingCaptureMode.video;
            cameraSettings.videoDeviceId = videodeviceid;
    
            preview(cameraSettings);
        }
    
    
        function stopcapture() {
            mediaCapture = null;
            previewvid.src = null;
        }
    
       var tempres = [];
        var newresX;
        var newresY;
        var newres;
        function preview(cameraSettings) {
            mediaCapture = new Windows.Media.Capture.MediaCapture();
    
    
    
            //mediaCapture.addEventListener("failed", onCameraError, false);
            mediaCapture.initializeAsync(cameraSettings).then(function () {
                mediaCapture.setPreviewRotation(Windows.Media.Capture.VideoRotation.clockwise90Degrees);
                return getCameraResolutions();
    
            }).then(function () {
                previewvid.src = URL.createObjectURL(mediaCapture, {oneTimeOnly:true});
                previewvid.play();
            },
            function (error) {
                showError(error);
            });
        }
    
    
        // Get all resolutions of current MediaCapture object and populate resolutions option in UI 
        // Return a Promise when completed
        function getCameraResolutions() {
            if (mediaCapture) {
                cameraResolutions = [];
                while (selectResolutions.length > 0) {
                    selectResolutions.remove(0);
                }
    
                var currentResolution = mediaCapture.videoDeviceController.getMediaStreamProperties(mediaType.videoPreview);
                var allResolutions = mediaCapture.videoDeviceController.getAvailableMediaStreamProperties(mediaType.videoPreview);
    
                // Save all unique resolutions
                var tempResolutions = [];
                for (var i = 0; i < allResolutions.length; i++) {
                    var res = allResolutions[i];
                    if (res.width < 600)
                        continue;
                    var hasDuplicated = false;
                    tempResolutions.forEach(function (item) {
                        if (item.width == res.width && item.height == res.height)
                            hasDuplicated = true;
                   });
                    if (!hasDuplicated)
                        tempResolutions.push(res);
                }
    
                // Sort all unique resolutions from low to high based on width
                tempResolutions.sort(function (item1, item2) {
                    return item1.width == item2.width ? item1.height - item2.height : item1.width - item2.width;
                });
    
                // Save camera resolutions and populate resolution options in UI 
                for (var i = 0; i < tempResolutions.length; i++) {
                    var res = tempResolutions[i];
                    cameraResolutions.push(res);
                    selectResolutions.add(new Option(res.width + "x" + res.height));
                    if (currentResolution.width == res.width && currentResolution.height == res.height) {
                        selectResolutions.selectedIndex = i;
                    }
                }
                return mediaCapture.videoDeviceController.setMediaStreamPropertiesAsync(mediaType.videoPreview, currentResolution);
            } else {
                return WinJS.Promise.as();
            }
        }
    
        // Switch to a different resolution on a camera
        function setCameraResolution() {
            if (mediaCapture) {
                try {
                    var index = selectResolutions.selectedIndex;
                    if (cameraResolutions.length > index) {
                        var resolution = cameraResolutions[index];
                        mediaCapture.videoDeviceController.setMediaStreamPropertiesAsync(mediaType.videoPreview, resolution).then(function () {
                            previewvid.src = null;
                            previewvid.src = URL.createObjectURL(mediaCapture, { oneTimeOnly: true });
                            previewvid.play();
                        },
                        function (error) {
                            onCameraError(error);
                        });
                    }
                } catch (e) {
                    showError(e);
                }
            }
        }
    
    
        function showError(error) {
            new Windows.UI.Popups.MessageDialog("Camera Not Initialized, Try again").showAsync();
        }
    
        function switchcam() {
            var deviceInfo = Windows.Devices.Enumeration.DeviceInformation;
    
            deviceInfo.findAllAsync(Windows.Devices.Enumeration.DeviceClass.videoCapture).then(function (devices) {
                if (devices.length > 0) {
                    var defaultcam = devices[1];
                    for (var i = 0; i < devices.length; i++) {
                        var device = devices[i];
                        allcameras.push(device);
                        if (device.enclosureLocation && device.enclosureLocation.panel == Windows.Devices.Enumeration.Panel.back) {
                            defaultcam = device;
                        }
                    }
                }
    
                var length;
    
                var currentcamid = mediaCapture.mediaCaptureSettings.videoDeviceId;
                for (var i = 0; i < 2; i++) {
                    var cam = allcameras[i];
                    if (currentcamid.toLowerCase() === cam.id.toLowerCase()) {
                        length = allcameras.length;
                        if (allcameras.length == 4) {
                            length = 2;
                        }
    
                        if (i == (length - 1)) {
                            nextcamera = allcameras[i - 1];
                        }
                        else {
                            nextcamera = allcameras[i + 1];
                        }
                        if (nextcamera) {
                            stopcapture();
                            init(nextcamera.id);
    
                            break;
                        }
    
                    }
    
                }
    
            });
        }
    
        function fun() {
    
            Windows.Storage.ApplicationData.current.localFolder.createFileAsync("photo.jpg", Windows.Storage.CreationCollisionOption.openIfExists).done(function (file) {
    
                mediaCapture.capturePhotoToStorageFileAsync(Windows.Media.MediaProperties.ImageEncodingProperties.createJpeg(), file).done(function (result) {
                    Windows.Storage.ApplicationData.current.localFolder.getFileAsync("photo.jpg").done(function (file) {
                        var url = URL.createObjectURL(file);
                        img1.src = url;
                    });
    
                });
            });
        }
    
        function custommessagedialog() {
            var cmd = new Windows.UI.Popups.MessageDialog("Test");
            cmd.commands.append(new Windows.UI.Popups.UICommand("Ok", function () {
    
            }));
            cmd.commands.append(new Windows.UI.Popups.UICommand("Cancel"));
            cmd.showAsync();
    
        }
    })();
    

    So I think the preview size will depend on the camera maximum resolution and how you set it.

    With Regards,

    Krunal Parekh


    Thanks MSDN Community Support Please remember to Mark as Answer the responses that resolved your issue. It is a common way to recognize those who have helped you, and makes it easier for other visitors to find the resolution later.

    Thursday, July 30, 2015 9:20 AM

All replies

  • Post the code you have done so far.

    http://stackoverflow.com/questions/18816441/how-to-open-camera-in-winjs


    Gaurav Khanna | Microsoft .NET MVP | Microsoft Community Contributor

    Thursday, July 2, 2015 4:20 PM
  • Post the code you have done so far.

    http://stackoverflow.com/questions/18816441/how-to-open-camera-in-winjs


    Gaurav Khanna | Microsoft .NET MVP | Microsoft Community Contributor

    Here is my code

    function initCam() {
        var deviceInfo = Windows.Devices.Enumeration.DeviceInformation;
        deviceInfo.findAllAsync(Windows.Devices.Enumeration.DeviceClass.videoCapture).done(function (devices) {
            videodeviceId = devices[1].id;  // getting Rear facing camera 
        });
        cameraSettings = new Windows.Media.Capture.MediaCaptureInitializationSettings();
        cameraSettings.photoCaptureSource = Windows.Media.Capture.PhotoCaptureSource.videoPreview;
        cameraSettings.streamingCaptureMode = Windows.Media.Capture.StreamingCaptureMode.video;
        cameraSettings.videoDeviceId = videodeviceId;
        previewCam(cameraSettings);
    
    }
    function previewCam(cameraSettings) {
        mediaCapture = new Windows.Media.Capture.MediaCapture();
        mediaCapture.initializeAsync(cameraSettings).done(function () {
            mediaCapture.setPreviewRotation(Windows.Media.Capture.VideoRotation.clockwise90Degrees);
            var currentres = mediaCapture.videoDeviceController.getMediaStreamProperties(Windows.Media.Capture.MediaStreamType.videoPreview);
            var res = mediaCapture.videoDeviceController.getAvailableMediaStreamProperties(Windows.Media.Capture.MediaStreamType.videoPreview);
            mediaCapture.videoDeviceController.setMediaStreamPropertiesAsync(Windows.Media.Capture.MediaStreamType.videoPreview, currentres).done(function () {
                previewVid.src = URL.createObjectURL(mediaCapture);
                previewVid.play();
            });
    
        }, function () {
            new Windows.UI.Popups.MessageDialog("Camera not Initialized, Please try again").showAsync().done(closeCamera());
        });
    }

    Friday, July 3, 2015 7:13 AM
  • Hello Ravindra Sharma, 

    Have you tried setting the width and height to 100% in the video html tag?

    Please see this: http://benhuang.blogspot.com/2013/05/implementing-camera-switch-resolution.html 

    HTML:

       <video id="cameraPreview"></video>
    CSS:
    #cameraPreview { width: 100%; height: 100%; }

    As far as I know setting the width and height 100% will show the preview according to the resolution of the camera.

    Hope this helps.

    With Regards,

    Krunal Parekh

    Wednesday, July 15, 2015 1:36 AM
  • Hi Krunal,

    I referred the same blog. I'm using the max resolution

    The <video> element is inside a <div>. The div is taking the whole screen, but not the preview.

     width: 100%;
        height: 100%;

    Used this for both video and Div elements, but somehow its not taking the whole screen.

    Monday, July 20, 2015 12:01 PM
  • Hello Ravindra Sharma,

    I was able to reproduce the issue with sample code you provided I tested it windows phone device and the preview was seeing small as you described.

    I putted a select for resolution in your html and populated the available resolutions and set the resolution at runtime. When I changed the option in resolution I could see that the preview size was actually changing according to the resolution. So I  think the issue is with resolution please see this code.

    HTML

    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8" />
        <title>App1</title>
    
        <!-- WinJS references -->
        <!-- At runtime, ui-themed.css resolves to ui-themed.light.css or ui-themed.dark.css
        based on the user’s theme setting. This is part of the MRT resource loading functionality. -->
        <link href="/css/ui-themed.css" rel="stylesheet" />
        <script src="//Microsoft.Phone.WinJS.2.1/js/base.js"></script>
        <script src="//Microsoft.Phone.WinJS.2.1/js/ui.js"></script>
        <script src="js/wincompact.js"></script>
    
        <!-- App1 references -->
        <link href="/css/default.css" rel="stylesheet" />
        <script src="/js/default.js"></script>
        <script src="js/MobileServices.Web-1.2.7.min.js"></script>
    
        <!-- <script src="js/MobileServices.intellisense.js"></script>-->
    </head>
    <body class="phone">
        <button id="capture">Capture</button> <button id="previewbtn">Preview</button> <button id="switchcambtn">Switch</button> <button id="stopcam">Stop</button>
        <select id="selectResolutions" title="Camera Resolutions"></select>
    
    
    
        <video id="previewvid" style="float:left;"></video>
    
        <img id="img1" />
    
    
    
    </body>
    </html>
    
    

    Javascript

    var mediaCapture = new Windows.Media.Capture.MediaCapture();
    var cameraSettings;
    var allcameras = [];
    var nextcamera;
    var videodeviceid;
    var mediaType = Windows.Media.Capture.MediaStreamType
    var cameraResolutions = [];
    
    (function () {
        "use strict";
    
        var app = WinJS.Application;
        var activation = Windows.ApplicationModel.Activation;
    
        app.onactivated = function (args) {
            if (args.detail.kind === activation.ActivationKind.launch) {
                if (args.detail.previousExecutionState !== activation.ApplicationExecutionState.terminated) {
                    // TODO: This application has been newly launched. Initialize
                    // your application here.
                } else {
                    // TODO: This application has been reactivated from suspension.
                    // Restore application state here.
                }
                args.setPromise(WinJS.UI.processAll());
                var x = document.getElementById("capture");
                x.addEventListener("click", fun, false);
    
                previewbtn.addEventListener("click", preview, false);
                stopcam.addEventListener("click", stopcapture, false);
                switchcambtn.addEventListener("click", switchcam, false);
                selectResolutions.addEventListener("change", setCameraResolution);
                var deviceInfo = Windows.Devices.Enumeration.DeviceInformation;
                deviceInfo.findAllAsync(Windows.Devices.Enumeration.DeviceClass.videoCapture).done(function (devices) {
                    videodeviceid = devices[0].id; // opening rare face camera
                });
    
                init(videodeviceid);
    
    
            }
        };
    
        app.oncheckpoint = function (args) {
            // TODO: This application is about to be suspended. Save any state
            // that needs to persist across suspensions here. You might use the
            // WinJS.Application.sessionState object, which is automatically
            // saved and restored across suspension. If you need to complete an
            // asynchronous operation before your application is suspended, call
            // args.setPromise().
        };
    
    
        app.start();
    
    
    
        function init(videodeviceid) {
            cameraSettings = new Windows.Media.Capture.MediaCaptureInitializationSettings();
            cameraSettings.photoCaptureSource = Windows.Media.Capture.PhotoCaptureSource.videoPreview;
            cameraSettings.streamingCaptureMode = Windows.Media.Capture.StreamingCaptureMode.video;
            cameraSettings.videoDeviceId = videodeviceid;
    
            preview(cameraSettings);
        }
    
    
        function stopcapture() {
            mediaCapture = null;
            previewvid.src = null;
        }
    
       var tempres = [];
        var newresX;
        var newresY;
        var newres;
        function preview(cameraSettings) {
            mediaCapture = new Windows.Media.Capture.MediaCapture();
    
    
    
            //mediaCapture.addEventListener("failed", onCameraError, false);
            mediaCapture.initializeAsync(cameraSettings).then(function () {
                mediaCapture.setPreviewRotation(Windows.Media.Capture.VideoRotation.clockwise90Degrees);
                return getCameraResolutions();
    
            }).then(function () {
                previewvid.src = URL.createObjectURL(mediaCapture, {oneTimeOnly:true});
                previewvid.play();
            },
            function (error) {
                showError(error);
            });
        }
    
    
        // Get all resolutions of current MediaCapture object and populate resolutions option in UI 
        // Return a Promise when completed
        function getCameraResolutions() {
            if (mediaCapture) {
                cameraResolutions = [];
                while (selectResolutions.length > 0) {
                    selectResolutions.remove(0);
                }
    
                var currentResolution = mediaCapture.videoDeviceController.getMediaStreamProperties(mediaType.videoPreview);
                var allResolutions = mediaCapture.videoDeviceController.getAvailableMediaStreamProperties(mediaType.videoPreview);
    
                // Save all unique resolutions
                var tempResolutions = [];
                for (var i = 0; i < allResolutions.length; i++) {
                    var res = allResolutions[i];
                    if (res.width < 600)
                        continue;
                    var hasDuplicated = false;
                    tempResolutions.forEach(function (item) {
                        if (item.width == res.width && item.height == res.height)
                            hasDuplicated = true;
                   });
                    if (!hasDuplicated)
                        tempResolutions.push(res);
                }
    
                // Sort all unique resolutions from low to high based on width
                tempResolutions.sort(function (item1, item2) {
                    return item1.width == item2.width ? item1.height - item2.height : item1.width - item2.width;
                });
    
                // Save camera resolutions and populate resolution options in UI 
                for (var i = 0; i < tempResolutions.length; i++) {
                    var res = tempResolutions[i];
                    cameraResolutions.push(res);
                    selectResolutions.add(new Option(res.width + "x" + res.height));
                    if (currentResolution.width == res.width && currentResolution.height == res.height) {
                        selectResolutions.selectedIndex = i;
                    }
                }
                return mediaCapture.videoDeviceController.setMediaStreamPropertiesAsync(mediaType.videoPreview, currentResolution);
            } else {
                return WinJS.Promise.as();
            }
        }
    
        // Switch to a different resolution on a camera
        function setCameraResolution() {
            if (mediaCapture) {
                try {
                    var index = selectResolutions.selectedIndex;
                    if (cameraResolutions.length > index) {
                        var resolution = cameraResolutions[index];
                        mediaCapture.videoDeviceController.setMediaStreamPropertiesAsync(mediaType.videoPreview, resolution).then(function () {
                            previewvid.src = null;
                            previewvid.src = URL.createObjectURL(mediaCapture, { oneTimeOnly: true });
                            previewvid.play();
                        },
                        function (error) {
                            onCameraError(error);
                        });
                    }
                } catch (e) {
                    showError(e);
                }
            }
        }
    
    
        function showError(error) {
            new Windows.UI.Popups.MessageDialog("Camera Not Initialized, Try again").showAsync();
        }
    
        function switchcam() {
            var deviceInfo = Windows.Devices.Enumeration.DeviceInformation;
    
            deviceInfo.findAllAsync(Windows.Devices.Enumeration.DeviceClass.videoCapture).then(function (devices) {
                if (devices.length > 0) {
                    var defaultcam = devices[1];
                    for (var i = 0; i < devices.length; i++) {
                        var device = devices[i];
                        allcameras.push(device);
                        if (device.enclosureLocation && device.enclosureLocation.panel == Windows.Devices.Enumeration.Panel.back) {
                            defaultcam = device;
                        }
                    }
                }
    
                var length;
    
                var currentcamid = mediaCapture.mediaCaptureSettings.videoDeviceId;
                for (var i = 0; i < 2; i++) {
                    var cam = allcameras[i];
                    if (currentcamid.toLowerCase() === cam.id.toLowerCase()) {
                        length = allcameras.length;
                        if (allcameras.length == 4) {
                            length = 2;
                        }
    
                        if (i == (length - 1)) {
                            nextcamera = allcameras[i - 1];
                        }
                        else {
                            nextcamera = allcameras[i + 1];
                        }
                        if (nextcamera) {
                            stopcapture();
                            init(nextcamera.id);
    
                            break;
                        }
    
                    }
    
                }
    
            });
        }
    
        function fun() {
    
            Windows.Storage.ApplicationData.current.localFolder.createFileAsync("photo.jpg", Windows.Storage.CreationCollisionOption.openIfExists).done(function (file) {
    
                mediaCapture.capturePhotoToStorageFileAsync(Windows.Media.MediaProperties.ImageEncodingProperties.createJpeg(), file).done(function (result) {
                    Windows.Storage.ApplicationData.current.localFolder.getFileAsync("photo.jpg").done(function (file) {
                        var url = URL.createObjectURL(file);
                        img1.src = url;
                    });
    
                });
            });
        }
    
        function custommessagedialog() {
            var cmd = new Windows.UI.Popups.MessageDialog("Test");
            cmd.commands.append(new Windows.UI.Popups.UICommand("Ok", function () {
    
            }));
            cmd.commands.append(new Windows.UI.Popups.UICommand("Cancel"));
            cmd.showAsync();
    
        }
    })();
    

    So I think the preview size will depend on the camera maximum resolution and how you set it.

    With Regards,

    Krunal Parekh


    Thanks MSDN Community Support Please remember to Mark as Answer the responses that resolved your issue. It is a common way to recognize those who have helped you, and makes it easier for other visitors to find the resolution later.

    Thursday, July 30, 2015 9:20 AM