WinJS / WinRT: detect corrupt image file - windows-8

I'm building a Win8/WinJS app that loads pictures from the local pictures library. Everything is generally working fine for loading valid images and displaying them in a list view.
Now I need to detect corrupt images and disable parts of the app for those images.
For example, open a text file and enter some text in it. Save the file as .jpg, which is obviously not going to be a valid jpg image. My app still loads the file because of the .jpg name, but now I need to disable certain parts of the app because the image is corrupt.
Is there a way I can check to see if a given image that I've loaded is a valid image file? To check if it's corrupt or not?
I'm using standard WinRT / WinJS objects like StorageFile, Windows.Storage.Search related objects, etc, to load up my image list based on searches for file types.
I don't need to filter out corrupt images from the search results. I just need to be able to tell if an image is corrupt after someone selects it in a ListView.

One possible solution would be to check the image's width and height properties to determine whether it is valid or not.

Yeah, the contentType property will return whatever the file extension is. The best way I can find it to look at the image properties:
file.properties.getImagePropertiesAsync()
.done(function(imageProps) {
if(imageProps.width === 0 && imageProps.height === 0) {
// I'm probably? likely? invalid.
});

where SelectImagePlaceholder is an Image Control.. =)
StorageFile file;
using (IRandomAccessStream fileStream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read))
{
try
{
// Set the image source to the selected bitmap
BitmapImage bitmapImage = new BitmapImage();
await bitmapImage.SetSourceAsync(fileStream);
SelectImagePlaceholder.Source = bitmapImage;
//SelectImagePlaceholder.HorizontalAlignment = HorizontalAlignment.Center;
//SelectImagePlaceholder.Stretch = Stretch.None;
this.SelectImagePlaceholder.DataContext = file;
_curMedia = file;
}
catch (Exception ex)
{
//code Handle the corrupted or invalid image
}
}

Related

How do you add a picture to the ID3 Album tag using taglib#

I've been searching the internet and trying various methods to save a picturbox image to the the id3 Album picture tag. One sample code says the Album cover tag name is taglib.ipicture another says taglibVariable.Image and yet another says taglibVariable.picture(0).
I am becoming so confused I'm starting to repeat sample test code.
Where is the documentation that will explain what I have to do.?
What little information I can find are dead links to sample code or incomplete code using variables without explanations. When I look up the commands and try to format or convert to the needed data type, I get an error. Usually system.image.bmp cannot be converted to iPicture.
Can anyone give me some working code or a pointer on how to word the proper search term to add a picturebox.image to the Album picture tag. Saving the image as a file then opening as image to put in tag then deleting file is not an option. I need to create a memory image and add that to the picture tag.
This is what I use:
public void SavePicture(string fileName, string picName) {
try {
IPicture[] pics = new TagLib.IPicture[1];
pics[0] = new TagLib.Picture(picName);
using (var songTag = TagLib.File.Create(fileName)) {
songTag.Tag.Pictures = pics;
songTag.Save();
}
}
catch {
// process
// mpeg header is corrupt
}
}
fileName is the full path to the audio file;
picName is the full path to the picture.
You can add multiple pics by setting the array size for the IPicture array accordingly...

Blob Storage Images - Azure

I have some problems with images that I upload through my web api to a public container in my blob storage. The problem is that i need the image i uploaded through my api have to be browseable, i mean when put the public link in a browser you can see the image in the browser, but the actual behavior is that when i put the link the image make a download of the image and doesnt show me nothing in the browser But when i Upload the image through the azure portal i can see the image as I want.... I have my container public and i dont know what else to do.... my code to upload a image is this:
private readonly CloudBlobContainer blobContainer;
public UploadBlobController()
{
var storageConnectionString = ConfigurationManager.AppSettings["StorageConnectionString"];
var storageAccount = CloudStorageAccount.Parse(storageConnectionString);
var blobClient = storageAccount.CreateCloudBlobClient();
blobContainer = blobClient.GetContainerReference("messagesthredimages");
blobContainer.CreateIfNotExists();
blobContainer.SetPermissions(new BlobContainerPermissions { PublicAccess = BlobContainerPublicAccessType.Blob });
}
[HttpPost]
[Route("UploadImagetoBlob")]
public async Task<IHttpActionResult> UploadImagetoBlob()//string imagePath
{
try
{
var image = WebImage.GetImageFromRequest();
var imageBytes = image.GetBytes();
var blockBlob = blobContainer.GetBlockBlobReference(image.FileName);
blockBlob.Properties.ContentType = "messagesthreadimages/" + image.ImageFormat;
await blockBlob.UploadFromByteArrayAsync(imageBytes, 0, imageBytes.Length);
return Ok(blockBlob.Uri.ToString());
}
catch (Exception)
{
return BadRequest();
}
}
Examples, I hope somebody can help me with this.
What I Want => Correct
What I dont Want => Incorrect
I have faced the same issue before. Browsers download a file when they do not know the format (file type). If you monitor the files with the desktop app (no sure where this option is in the portal), you will find the file types.
These file types are set based on the blockBlob.Properties.ContentType you are setting. You need to inspect and check what exactly image.ImageFormat returns. The browser would only display the image if the this value is set to something like "image/jpeg". However since you are using "messagesthreadimages/" + image.ImageFormat, it might be setting something like "messagesthreadimages/image/jpeg".
As Neville said, you have some misunderstand when you call SetProperties method like blockBlob.Properties.ContentType.
Content-Type indicates the media type of the message content.
The image content type allows standardized image files to be included in messages. For more detail,you could refer to this link.
image/g3fax [RFC1494]
image/gif [RFC1521]
image/ief (Image Exchange Format) [RFC1314]
image/jpeg [RFC1521]
image/tiff (Tag Image File Format) [RFC2301]
I read this article and it seems that you would customize the ContentType of image.
So, you could change code as below:
blockBlob.Properties.ContentType = "image/" + image.ImageFormat;

How to Display Image Produced from byte in MVC 4

I'm new to MVC and I'm stuck with a problem I need to display an image which is stored in database as byte in my MVC 4 application I know how to produce the image from the byte but I dont know how to display it in the App. how can I solve this
If you want to display the image directly from the db, you need a controller that delivers the image and call that controller in the view. This posts shows how to do it:
Display image from database in _layout in mvc4
Cheers,
Rob
If you have the FileData as a byte[] and the mime type as a string, then try this controller method:
public FileContentResult Get(Guid fileId)
{
var file = _fileService.GetFile(fileId);
if (file != null)
{
return File(file.FileData, file.MimeType);
}
else
{
// Return 1x1px transparent png (67 bytes) - This is a clever trick of mine to serve an empty image without reading it from the disk. You may not want to do this!
return File(Convert.FromBase64String("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAACklEQVR4nGMAAQAABQABDQottAAAAABJRU5ErkJggg=="), "image/png");
}
}
Then in your view you need the URL to the image, which is obtained by doing this:
<img src="#Url.Action("Get", new {fileId = item.ID})" />

How to set Background of a Button without flicker?

I am trying to change the Background of a button to an image source. I want to load that image in memory when we navigate to the page so that it doesn't flicker the first time it shows.
On Windows Phone, I was able to create the image source as such:
StreamResourceInfo resourceInfo = Application.GetResourceStream(uri);
BitmapImage bitmapSource = new BitmapImage();
// Avoid flicker by not delay-loading.
bitmapSource.CreateOptions = BitmapCreateOptions.None;
bitmapSource.SetSource(resourceInfo.Stream);
imageSource = bitmapSource;
I tried something similar in my Windows 8 Store app:
BitmapImage bitmapSource = new BitmapImage();
bitmapSource.CreateOptions = BitmapCreateOptions.None;
bitmapSource.UriSource = uri;
imageSource = bitmapSource;
but the same problem occurs. The button already has a different image as the Background, and on a certain event I would like it to change to the new background. But when I change the source, a noticeable flicker is observed. I'm assuming this is because the image is not yet in memory, as the issue goes away the second time the image source is modified.
Anyone know a solution? I need to somehow force the loading of this image.
Thanks!
If you use the SetSourceAsync method on the BitmapImage and await it before you attach it to the image source you should not see the flicker:-
// Ensure the stream is disposed once the image is loaded
using (IRandomAccessStream fileStream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read))
{
// Set the image source to the selected bitmap
BitmapImage bitmapImage = new BitmapImage();
await bitmapImage.SetSourceAsync(fileStream);
imageSource = bitmapImage;
}
The MSDN docs have some more info on this
Thanks Ross, but what I ended up doing instead is I preloaded the half dozen or so bitmaps I needed by using similar code to what you had above, except from resource of course. I did this asynchronously when the page loaded, and then when I set the ImageSource on the button background, I used the already preloaded bitmaps. That way I know I'm not allocated a new chunk of memory for every instance of the bitmap.

Can't Save Image Blob

I am trying to save an image from the photo gallery to local storage so that I can load the image up across application sessions. Once the user is done selecting the image, the following logic is executed. On the simulator I see the error message is written out to the log. Even though I am seeing the error message I think the image is still saved in the simulato because when I restart the application I am able to load the saved image. When I run this on the device though, I still get the error message you see in the code below and the default background is loaded which indicates the write was not successful.
Can anyone see what I am doing wrong and why the image won't save successfully?
var image = i.media.imageAsResized(width, height);
backgroundImage.image = image;
function SaveBackgroundImage(image)
{
var file = Ti.Filesystem.getFile(Titanium.Filesystem.applicationDataDirectory,W.CUSTOM_BACKGROUND);
if(file.write(image, false))
{
W.analytics.remoteLog('Success Saving Background Image');
}
else
{
W.analytics.remoteLog('Error Saving Background Image');
}
file = null;
}
Try this Code:
var parent = Titanium.Filesystem.getApplicationDataDirectory();
var f = Titanium.Filesystem.getFile(parent, 'image_name.png');
f.write(image);
Ti.API.info(f.nativePath); // it will return the native path of image
In your code i thing you are not giving the type of the image (png/jpeg) thats why your getting error.