How to Display Image Produced from byte in MVC 4 - asp.net-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})" />

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;

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.

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

Sql - Reading images from DB

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?