How do I reduce the size of a WinJS image file

Can anyone help me figure out how to retrieve the size (in pixels, bytes) of a picture in a Windows 8 app? I'm using openPicker to select the file but can't seem to find the size attributes. I want to display an error message if the file is too large. Any suggestions on how to obtain this information would be greatly appreciated. Thanks!

Answer №1

To access necessary information from the StorageFile object, there's no need to open or load the file into memory.

Let's assume myFile represents the StorageFile being used.

To obtain image dimensions, utilize myFile.properties.getImagePropertiesAsync. This will return an ImageProperties object containing width and height properties. An example of how to retrieve ImageProperties can be found in the Simple imaging sample, scenario 1.

For file size, use myFile.getBasicPropertiesAsync. This function will provide a BasicProperties object with the corresponding size property value.

Answer №2

After spending several hours searching and experimenting, I finally found a solution that worked for me:

//insert image
        document.getElementById("btnAddImg").addEventListener('click', function () {
            // Create the picker object and specify options
            var openPicker = new Windows.Storage.Pickers.FileOpenPicker();
            openPicker.viewMode = Windows.Storage.Pickers.PickerViewMode.thumbnail;
            openPicker.suggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.picturesLibrary;
            openPicker.fileTypeFilter.replaceAll([".png", ".jpg", ".jpeg"]);
            openPicker.pickSingleFileAsync().then(function (file) {
                file.openAsync(Windows.Storage.FileAccessMode.read).done(function (stream) {
                    var fileType = file.contentType;
                    var blob = MSApp.createBlobFromRandomAccessStream(fileType, stream);
                    var fdata = new FormData();
                    fdata.append('upload_field', blob);
                    //additional code....
                });
            });
        });

I hope this solution can assist others facing similar challenges.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to incorporate data from a foreach method into a function call within an HTML string?

Having trouble calling a function with data from a foreach loop while generating HTML cards and buttons from an array. The issue seems to be in the renderProducts() method. /// <reference path="coin.ts" /> /// <reference path="prod ...

The v-list-group does not automatically expand sub-groups based on the path specified in the group prop

I have a navigation sidebar that includes nested v-list-groups. Based on the documentation, the "group" prop of v-list-group should expand based on the route namespace. To see more information, visit: https://vuetifyjs.com/en/components/lists/ While this ...

Display the div if the input field is left blank

Is there a way to display the div element with id="showDiv" only if the input field with id="textfield" is empty? <form action=""> <fieldset> <input type="text" id="textfield" value=""> </fieldset> </form> <div id="sh ...

Analyzing latency in node.js through numerous requests

Is there a way to send multiple requests in a loop, and measure the time of each request? In PHP I'd do: require 'vendor/autoload.php'; use GuzzleHttp\Client; $client = new Client(); for ($i = 0; $i < 100; $i++) { $start = mic ...

Dynamically populating checkboxes and dynamically setting their checked state

I'm working with a for loop that dynamically generates 7 checkboxes in a row. Here's how it looks: @for (int i = 1; k < order.Rows.length; i++) { Row: @i <ul> @for (int j = 1; j < order.NumCheckboxes.length; j++) ...

leveraging dependency injection to retrieve a function in JavaScript

I'm exploring a way to obtain a function in JavaScript without executing it, but still defining the parameters. My current project involves creating a basic version of Angular's dependency injection system using Node.js. The inject() method is us ...

Verifying whether every value in the X array is present in the Y array or not

Currently, I am working with two arrays: const arrA = [1, 2, 3, 4, 5]; const arrB = [1, 2, 3, 4, 5, 6, 7, 8, 9]; My goal is to determine if all elements in array A exist in array B. Here are a few scenarios for better clarity: const arrA = [1, 2, 3, 4, ...

Subclassing Observable in RxJS 5: Parent class instances are returned by static methods

I've been experimenting with subclassing the RxJS Observable class and overriding the lift method, as explained here. While I can successfully add new operators to the prototype, when trying to create a new Observable using my subclass (such as MyObs ...

appending a set of parameters to a website address

I am currently developing an app in a Node/Express/Jade environment. Imagine that I launch my app and navigate my browser to the following URL: /superadmin/?year=2012 Upon reaching this page, I encounter a list of objects sorted in a default order. Ther ...

retrieve the timestamp when a user initiates a keystroke

Seeking assistance from the community as I have been struggling with a problem for days now. Despite searching on Google and Stack Overflow, I haven't found a solution that works for me. My web application features an analog clock, and I need to capt ...

Utilize ng-click in conjunction with an AngularJS directive

I'm encountering an issue while trying to create a directive and attaching ng-click with the template. Despite my efforts, when clicking on the template, it fails to log the statement from the scope.scrollElem function. The directive has been success ...

Tips on incorporating asynchronous functionality in AngularJS

I am currently utilizing AngularJS version 1.5.8 and have a specific requirement. When the user clicks on the Next button, the text inside the button should change to 'Processing...' before completing the operation. I have implemented the $q serv ...

Error: Unexpected termination of data in JSON file on line 2, starting at the first character

I keep encountering an error while trying to execute a basic JSON request. Check out the following PHP code that contains the data: <?php header('Content-Type: application/json; charset=utf-8'); $wealth = array( "name" => &q ...

Implementing automatic number increment in Vue.js forms

I have a field where I can enter numbers <input type="text" class="form-control" id="validationTooltip01" v-model="verse.number" required> After saving the number in the database, I would like it to automatically increment. For example: If I inpu ...

Text that fades in and out based on scrolling past a specific point

There's a text containing <p> and <h1>. The text finishes with one <h1>. I'm looking to speed up the Y translation of the <p> twice when I reach the bottom of the document (where the last h1 is located in the middle of th ...

The response from NodeJS is not being properly parsed by Express or BodyParser

const express = require('express'); const bodyParser = require('body-parser'); const app = express(); const adminRoutes = require('./routes/admin'); const shopRoutes = require('./routes/shop'); // app.use(express.u ...

Error in Bootstrap table implementation leading to truncation of tbody height due to data-detail-view property

I'm currently working on integrating Bootstrap-Table's detailView feature into my project. However, when I enable data-detail-view="true" for my table, the height of the table element shrinks to 0. Strangely, clicking on any column with ...

PHP Ajax login form to instantly authenticate without redirecting to a new page

After attempting to implement Ajax in my login form by following two different tutorials, I am still facing the issue of error messages redirecting to another page instead of displaying on the same page. I have tried to troubleshoot and compare my code wit ...

Synchronize numerous PouchDB databases with a single CouchDB database

After reading the PouchDB documentation, I learned that sync occurs between a local database and a remote CouchDB database. Currently, I am working on developing a native application that includes a unique local database for each user (multiple databases) ...

Preloading images before loading a div using JavaScript

Can you walk me through implementing object first and then mergeObject in JavaScript? I have an interesting scenario where I need to display the original list followed by a merged list after a short delay. How can I achieve this using JavaScript? Specific ...