Check for Valid Image using getFilesAsync() - png

Using WinJS, while looping through a directory, how to retrieve only images in that particular directory and ignoring any other file extension, including the DoubleDots .. and the SingleDot . etc?
Something like:
var dir = Windows.Storage.KnownFolders.picturesLibrary;
dir.getFilesAsync().done(function (filesFound) {
for(var i=0; i < filesFound.length; i++){}
if(filesFound[i] IS_REALLY_AN_IMAGE_(jpeg,jpg,png,gif Only)){
//Retrieve it now!
}else{
//Escape it.
}
}})

Instead of trying to process pathnames, it will work much better to use a file query, which lets the file system do the search/filtering for you. A query also allows you to listen for the query's contentschanged event if you want to dynamically track the folder contents rather than explicitly enumerating again.
A query is created via StorageFolder.createFileQuery, createFolderQuery, or other variants. In your particular case, where you want to filter by file types, you can use createFileQueryWithOptions. This function takes a QueryOptions object which you can initialize with an array of file types. For example:
var picturesLibrary = Windows.Storage.KnownFolders.picturesLibrary;
var options = new Windows.Storage.Search.QueryOptions(
Windows.Storage.Search.CommonFileQuery.orderByName, [".jpg", ".jpeg", ".png", ".gif"]);
//Could also use orderByDate instead of orderByName
if (picturesLibrary.areQueryOptionsSupported(options)) {
var query = picturesLibrary.createFileQueryWithOptions(options);
showResults(query.getFilesAsync());
}
where showResults is some function that takes the promise from query.getFilesAsync and iterates as needed.
I go into this subject at length in Chapter 11 of my free ebook, Programming Windows Store Apps with HTML, CSS, and JavaScript, 2nd Edition, in the section "Folders and Folder Queries". Also refer to the Programmatic file search sample, as I do in the book.
When you want to display the image files, be sure to use thumbnails instead of loading the whole image (images are typically much larger than a display). That is, for each StorageFile, call its getThumbnailAsync or getScaledImageAsThumbnailAsync method. Pass the resulting thumbnail (blob) to URL.createObjectURL which returns a URL you can assign to an img.src attribute. Or you can use a WinJS.UI.ListView control, but that's another topic altogether (see Chapter 7 of my book).

Related

How to get the content of all files in a given directory?

Octokit allows me to easily retrieve the list of files in a given folder like so:
var directoryContent = await _githubClient.Repository.Content.GetAllContents("MyUsername", "MyProject", "TheFolderName").ConfigureAwait(false);
Unfortunately, the Content property for each file is null which means that I have to loop through the list of files and retrieve each one separately like so:
foreach (var file in directoryContent)
{
var fileWithContent = await _githubClient.Repository.Content.GetAllContents("MyUsername", "MyProject", file.Path).ConfigureAwait(false);
... do something with the content ...
}
Is there a more efficient way to get the content of all files in a given folder?
Just for reference: This is on purpose. If you read a whole directory and load all the content in one step it's huge load. So, the first call skips the content (Content property is null). The second step requests just this file and then the content is present.
Only thing I'm still missing is a method that can return just one result instead of a list if I pull a single file.

Get the list of PNG files in File Storage excluding _processed_ folder

As topic says, I need to get only unprocessed PNG files.
My current approach is the following:
$fileExtensionFilter = $this->objectManager->get(FileExtensionFilter::class);
$fileExtensionFilter->setAllowedFileExtensions('png');
$storage->addFileAndFolderNameFilter([$fileExtensionFilter, 'filterFileList']);
$availablePngFiles = $storage->getFileIdentifiersInFolder($storage->getRootLevelFolder(false)->getIdentifier(), true, true);
foreach ($availablePngFiles as $pngFile) {
if(!$storage->isWithinProcessingFolder($pngFile)) {
$pngFileObject = $storage->getFile($pngFile);
}
}
So, it works, but I'd like to avoid the unnecessary isWithinProcessingFolder() lookup and get only the original unprocessed files, which will significantly reduce the number of loops.
TYPO3 core 7.6.19 does only ship with two filters: FileExtensionFilter and FileNameFilter, which actually is a "hidden file filter".
You could write your own file filter and filter in there, but that's way more work than keeping those two lines of code.

Symfony FileFormField - Testing (WebTestCase) multiple file upload

In my Symfony web application I have a form allowing multiple file upload (easily done by setting the multiple property of the FileType equal to true). And this works fine: I can select multiple files and upload them. Processing the form and getting all uploaded files also goes fine. But of course, I want to foresee an integration test (WebTestCase) but I don't find any possibility to simulate a multiple file upload.
What I have now:
...
$uploadedFile = new UploadedFile(...);
$form = ...; // get the form from the crawler
$form['formtype[filename]'][0]->upload($uploadedFile);
$this->client->submit($form);
...
That works fine.
But now I want to upload 2 files by 1 form submission (because the processing logic can behave differently when multiple files are uploaded at once). How can I do this? When I look at http://api.symfony.com/3.0/Symfony/Component/DomCrawler/Field/FileFormField.html I don't see any way to pass in, for example, an array of UploadedFile objects. Anyone experience with this?
If the multiple property is set, crawler creates a file form field array with single FileFormField field. One field can hold a single file so you need multiple fields for multiple files. I came to a solution by manually adding more FileFormField to the form.
$form = ...
// get file field node in DOM
$node = $crawler->filter("input[name='formtype[filename][]']")->getNode(0);
// add additional fields to form (you can create as many as you need)
$newField = new FileFormField($node);
$form->set($newField);
...
// set files with upload()
$form['formtype[filename]'][0]->upload($uploadedFile1);
$form['formtype[filename]'][1]->upload($uploadedFile2);
...
//or with submit values
$crawler->submit($form, [
...
'formtype[filename]' => [$uploadedFile1, $uploadedFile2]
]);

RMagick & Sinatra: send picture to view without storing

Currently I am writing a Sinatra app that gets some pictures from user and returns a new picture.
There's part of haml form:
%input{type:'file', name:'user_image'}
And there's a code from handler: (montage is another picture)
source_userpic = params[:user_image][:tempfile]
blob = File.open(source_userpic).read
userpic = ImageList.new
userpic.from_blob(blob)
resized_img = userpic.scale(montage.columns,
montage.rows)
resized_img.opacity = MaxRGB/3
Then two images are "layered" with composite and stored (don't need)
final_picture = ImageList.new
final_picture << montage.composite(resized_img, 0, 0, OverCompositeOp)
final_picture.write("./public/uploads/#{DateTime.now}.jpg" # dirty (for example)
Next, I need to show a final_picture with ajax. There are two obvious problems: first, I don't need to save a final_picture - it's just preview, second, I must write code to avoid filenames conflicts...
How to send a final_picture to view? to_blob method? But what's next?
I solved that by using the data URI scheme.
require 'base64'
final_picture.format = "jpeg" # whatever
# Using a to_blob method to create a direct-to-memory version of the image.
# Then encode it to base64 string
data_uri = Base64.encode64(final_picture.to_blob).gsub(/\n/, "")
#image_tag = '<img alt="preview" src="data:image/jpeg;base64,%s">' % data_uri
haml:'pages/preview'
Then display a picture by
= #image_tag
Not sure if it's best solution
Take a look at Tempfile, that should take care of file name conflicts for you.
Then you could use the technique from the answers to this question, using send_file to send the tempfile.
You have to remember that the tempfile won't persist, so you have to be careful to manage that persistence if you are using different requests and responses to serve the file.

Eclipse - Export/Save Search Results

Eclipse's Search results view is quite handy with its tree-like structure. Is there any way to export these results to a readable text format or save them to a file for later use?
I've tried using copy & paste but the resulting text format is far from readable.
You can change the mode from tree to list by click 'upper-right corner triangle' ->'show in list', then just copy all the files in the list , it will be a perfect list of search result
I'm using Eclipse Search CSV Export.
No I don't think there is a possibility to export the results yet. (Update: Now there's a suitable plugin available). But you should be able to use the eclipse search framework programmatically an export the entries by yourself.
I did not test the following snipped but implemeted a custom search that way once (using the RetrieverAction class). You should be able to listen to search result changes without the action as well:
TextSearchQueryProvider provider= TextSearchQueryProvider.getPreferred();
// your input (you'll have to implement that one I think...)
TextSearchInput input = new TextSearchQueryProvider.TextSearchInput();
ISearchQuery query= provider.createQuery(input);
ISearchResult result = query.getSearchResult();
result.addListener(new ISearchResultListener() {
public void searchResultChanged(SearchResultEvent e) {
// -> export result
}
});
// run the query
NewSearchUI.runQueryInBackground(query);
Again: I did not test that at all and don't know if there is a better approach as well..