I have a field (the type is varbinary) in my database that respresent an image. I would to read this image and display it in my view. i read from database using ADO.
in my data service i have (this is part of private web api project):
img= (byte []) reader["Image"];
i convert varbinary to array of byte
the my view is basically :
<img src="data:image/tiff;base64, #Model.ImageSource" />
but in my controller im not able to create a base64 string to assign in view to img tag.
Another problem can be that image is stored as tiff format.
I have tried in controller to do (this is in another mvc project that recall web api):
// call my service that return me image
var result = await client.GetAsync("ImagesController/GetImageBytes/" + id);
// ImageSource is a property of my viewmodel
ImageSource=Convert.ToBase64String(result.Content.ReadAsStreamAsync().Result)
// or
ImageSource= Convert.ToBase64String(JsonConvert.DeserializeObject<Byte[]>(result.Content.ReadAsStringAsync().Result))
// or
ImageSource= Convert.ToBase64String(result.Content.ReadAsByteArrayAsync().Result)
but despite hundreds of attempts (really) Im not able to visualize anything. My view show image placeholder only.
Someone can help me?
Related
I have a profile page in my Angular (v8) project and normally I use the following approach in order to display user photo:
<img class="profile-user-img" src="./DemoController/GetPhoto?Id={{rec.Id}}" />
However, I think there is another way to bind the image via model.ts that is already filled from database as the other fields. By doing this I just send a single request to the database instead of twice and the photo data will be included in the model.ts. So, how can I do this? Should I need a special convert image data before rendering?
Note: I use byte[] as the data type of photo on C# side. Any idea?
Here is my model. ts below:
export interface IUserProfile {
Id: number;
Photo: string | ArrayBuffer;
NameSurname: string;
}
I think you can just use the byte array to fill the img.src attribute.
In your template to the component you can write as follows:
<img class="profile-user-img" src="data:image/gif;base64,{{Profile.Photo}}" />
Where in your component you have:
#Component({})
export class User {
Profile: UserProfile;
}
I want to let a user load an image from their gallery:
var imageIntent = new Intent();
imageIntent.SetType("image/*");
imageIntent.SetAction(Intent.ActionGetContent);
StartActivityForResult(Intent.CreateChooser(imageIntent, "Select photo"), REQUESTCODE);
This works fine: I can use the image in that activity. But I want to store the URI in the database so the image is associated with the object. I use:
_recipeImage.SetImageURI(data.Data);
model.ImageUrl = data.Data.ToString();
_recipeImage is just an image view I'm using to see if I actually got the image correctly for now.
When I save my model to the database I get a string that looks something like:
content://com.android.providers.downloads.documents/document/22
When the user opens this item later the image should load so I parse the string to a Uri. I try and set the image URI as I did before, but no image gets shown.
var uri = Android.Net.Uri.Parse(imageUrl);
imageView.SetImageURI(uri);
Is there a better/working way to do this?
I think you want to load image directly use URL, it's easier to use some third-party lib, for example Picasso.
Since it's a java lib, you can use Binding Library to use it in Xamarin.
After adding this lib into your project, you can simply code like this:
Picasso.With(this).Load(imageUrl).Into(imageView);
I have two identical images. One is saved as a .png in a folder, the other is saved as a SQLite blob in a database. I'm trying to figure out a good way to persist these images and show them in my view when needed.
I have two methods for trying to get these images into my view. The first one is reading the image files directly from the file system, converting them into a base64 string which I shove into a ViewBag. This method works fine.
The other method is trying to load the image blob directly from the database and then fetch the image from the Model in the view. This doesn't work so well.
Through a couple of breakpoints I've found out that there's a huge different between the base64 strings, depending on my method. I'm not sure why and what the difference between the SQLite image blob and the .png in my file system is, and any help would be appreciated since saving images in a folder seems like extra work, when I could just keep them in my database.
Loading from the file system:
public string FirstImagePath(string slideid, int well)
{
var firstPath = HttpContext.Current.Server.MapPath(slideid);
byte[] firstImageByteData = File.ReadAllBytes(firstPath + "_first" + well + ".png");
string firstImageBase64Data = Convert.ToBase64String(firstImageByteData);
string firstImageDataUrl = string.Format("data:image/png;base64,{0}", firstImageBase64Data);
return firstImageDataUrl;
}
Loading from SQLite db:
public byte[] FirstImage { get; set; }
public string FirstBase64Image
{
get { return ConvertImage(FirstImage);}
}
public string ConvertImage(byte[] imageBytes)
{
byte[] imageArray = imageBytes;
string imageBase64String = Convert.ToBase64String(imageBytes);
string imageDataString = string.Format("data:image/png;base64,{0}", imageBase64String);
return imageDataString;
}
Both methods have their advantages and disadvantages.
If you store your images in a DB it's very easy to move the application across different platforms without having to copy a lot of images. On the other hand your DB is going to get very large over time.
Storing images on disk allows you to overwrite them easily with a copy / paste job etc. However, if you have multiple web servers, you're going to have to make this change several times.
However, this isn't the main issue that I have with your approach. The problem is that you get the images, convert them to base64 and embed them in your output. This is bad practice for many reasons. Firstly, browsers are smart enough to load in multiple resources at a time. For instance, your browser can download multiple images at a time which will drastically increase page load speed. If you have the images embeded it becomes the responsibility of the html parser to render these images which in turn slows the overall download of the html document as it's larger.
I would recommend a hybrid of the two. Upload images to your database. Create an image handler in your application that retrieves an image from the DB and attempts to save it to the file system. If it's successful return this image. The next time you try to get this image (and it's not cached on the users machine) your handler can check the file system to see if it has already been created and return it.
This method gives you the advantages of both the DB and file structure methods. If you decide you need 10 web servers, all of your images will be stored in the DB, and the file system will be automatically populated with your images as and when you need them depending on which server receives the request. I recommend using a GUID or some unique id for your images.
You could even extend this further and pass height and width parameters to the image handler that will resize the image for you before sending it back to the client.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to show a image in database in the image control of Asp.net?
I am returning a list of products from a database. Inside this list i am saving database images as bytearrays. Currently I am displaying about 30 products on a page and i would like to add their images next to the product information. What would be the easiest way to go about this?
What I have:
public Image PopulatePicture()
{
Image newImage;
//Read image data into a memory stream
using (MemoryStream ms = new MemoryStream(ImageByteArray, 0, ImageByteArray.Length))
{
ms.Write(ImageByteArray, 0, ImageByteArray.Length);
//Set image variable value using memory stream.
newImage = Image.FromStream(ms, true);
}
return newImage;
}
I have an error on Image.FromStream (System.Web.UI.WebControls does not contain a definition for FromStream)
If your using Mvc its rather simple
Simply write an action such as the following
public FileContentResult Image()
{
//Get the Byte Array for your image
byte[] image = FilesBLL.GetImage();
//Return a jpg
//Note the second parameter is the files mime type
return File(image, "image/jpeg");
}
See This Link For Mime types
http://www.webmaster-toolkit.com/mime-types.shtml
I highly suggest adding a column to your files table to store mime types (determine this on upload)
And in your view put down an image like this
<img src='#Url.Action("GalleryMediumThumb")'/>
for webforms see
How to show a image in database in the image control of Asp.net?
You likely have a few issues here:
You are referencing an asp.net Image object (System.Web.UI.WebControls.Image) not the GDI+ System.Drawing.Image object that you want. Clarify your namespace.
You can't dispose the stream on the image. Drop the using block. https://stackoverflow.com/a/13696705/64262
You will need to write the resulting stream to the response stream (negating the need to convert it to an image in the first place), and then reference that endpoint from an <img> tag.
A generic ASP.NET Handler (*.ashx) could load the image from the database and stream it as a normal image to the browser.
May this http://coffeedrivendevelopment.net/2012/10/26/sharing-image-resources-between-wpf-and-asp-net/ will help you. It is about images in ressources, but the way is the same.
This is a variation on a question that has been asked here several times. One example: Display an image contained in a byte[] with ASP.Net MVC3. The question is how to render an image from a byte array.
In all those questions, there is an Action similar to one of the answers in the link I provided above:
public FileContentResult Display(string id) {
byte[] byteArray = GetImageFromDB(id);
return new FileContentResult(byteArray, "image/jpeg");
}
With an image tag similar to this:
<img src="#Url.Action("Display", new { id = Model.Id })" />
This is done because it's not possible to send a byte array through a GET request, so just the id is sent allowing a lookup in the Action method. I get this part, it's not the problem. What I'm trying to do is create a 'Preview' page, where they can check their work before saving in the database. They can see the layout of the Title, Text and Image and decide whether to save, or go back and Edit some more. Therefore, the 'GetImageFromDB(id)' part won't work, since the object has not been saved yet to the database.
Is there any way to accomplish this, or do I just have to save the byte array temporarily in the database and access it that way for the Preview page?
You need to store the uploaded file somewhere on the server if you want to show it later (as a preview or full size image). Whether it is the database or the file system it is up to you. So once the file is uploaded you could store it as a temporary file on some location on the server by renaming it using some unique Guid and return this Guid to the client so that it can create an action link to a preview controller action passing the Guid which will fetch the file from the temporary location and stream it to the client.