Sql - Reading images from DB - sql

I keep getting the error image icon when reading images from my DB.
Here is the HttpHandler code:
public void ProcessRequest(HttpContext context) {
....
//After we got the data table:
byte[] image = (byte[])dt.Rows[0]["Picture"];
context.Response.ContentType = dt.Rows[0]["PictureType"].ToString();
context.Response.BinaryWrite(image);
}
I do check and see that image is not null (Just a really big array, as it should be), and PictureType does save the type of the picture that was previously saved in the db. But I still see the error image icon when calling the handler:
<img src='myhandler.ashx?imgid=someid'/>
Any reason for this to happen?

Related

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;

PNG file is corrupt when reading back from SQL

I have a database program that stores images to the SQL DB and reads them back to be displayed in a WPF application. if i use Jpeg images it works fine, but if i use PNG images, which i wanted to use to try and keep the transparency ( which disappears anyway when stored ) most of the images come back corrupt.
this is the image that has been selected
i then save it to the db, and add the image the listview
then if i close the application and reload it, it pulls the image back from the db, you can see that it is corrupt in the listview
and then when i select it, the image control also shows the corrupted image
i am storing the image in code using a BitmapImage object, and use this to set the image.source, and also convert this to a byte[] for storing into the image field in the database.
i convert the bitmapimage to a Byte[] with the following line
command.Parameters.AddWithValue("#Image", ImageToByteArray(productImage.ProductImage));
and these are the functions to convert to and from a bitmapimage
private static BitmapImage BuildImage(byte[] image)
{
var bitmap = new BitmapImage();
bitmap.BeginInit();
MemoryStream mem = new MemoryStream(image);
bitmap.StreamSource = mem;
bitmap.CacheOption = BitmapCacheOption.OnLoad;
bitmap.EndInit();
//bitmap.Freeze();
return bitmap;
}
private static byte[] ImageToByteArray(BitmapImage image)
{
byte[] data;
JpegBitmapEncoder encoder = new JpegBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(image));
using (MemoryStream ms = new MemoryStream())
{
encoder.Save(ms);
data = ms.ToArray();
}
return data;
}
works fine with Jpegs, but then i have the white background to the images.
any help would be much appreciated.
"JpegBitmapEncoder" is a large clue. Surely you'd want "PNGBitmapEncoder"...?
As personal preference I would change your SQL data column to varbinary(MAX) and use stream and BinaryReader objects to upload the file.
However I think your issue is you are not using PngBitmapEncoder for the PNG you are using the JpegBitmapEncoder irrespective of filetype.
Hope this helps.

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})" />

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.

WinJS / WinRT: detect corrupt image file

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
}
}