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.
Related
I try to save my images on my server, but I can't let my server save file and virus because of that I want to get image content as pixels of rgb and after that I create image by myself.
I can't use bitmap (or other type in C# like bitmapImage, ... etc) and I don't know how I can do this with sixlabors.ImageSharp.
I have some code that I tried but I can't implement the exact logic that I want (code shown here):
[HttpPost("[action]")]
public async Task<IActionResult> Get([FromForm] ImageFormat file)
{
await using var memoryStream = new MemoryStream();
await file.File.CopyToAsync(memoryStream);
IImageFormat format;
using (var image = Image.Load(memoryStream.ToArray(), out format))
{
using (var output = new MemoryStream())
{
image.Save(output, format);
var responseType = format.Name.ToLower();
return File(output.ToArray(), "application/octet-stream", file.File.FileName);
}
}
return null;
}
Can anybody help me with this problem?
i don't see a reason to convert image into image: there are several format zip-algorythms etc.wich you have to support in that case. example jpg is not bitmap, there is convertion issue - quality of image becomes less each conversion time. Image itself is not executable - it can be used only as container for virus body, can't harm your OSystem itself, another executable part should works somewhere.
But even if you would like to store images on disk, in other format - you can convert image to base64 text (one line of code, like example) - it less harmful and well known way to work with any file type. you can zip image by cszip, you can change file name and extension to hide file type.
I don't see a reasson to convert one image to another for this scenario/task.
I have a large number of images on a Web server that need to be cropped. I would like to automate this process.
So my thought is to create a routine that, given the URL of the image, downloads the image, crops it, then uploads it back to the server (as a different file). I don't want to save the image locally, and I don't want to display the image to the screen.
I already have a project in C#.Net that I'd like to do this in, but I could do .Net Core if I have to.
I have looked around, but all the information I could find for downloading an image involves saving the file locally, and all the information I could find about cropping involves displaying the image to the screen.
Is there a way to do what I need?
It's perfectly possible to issue a GET request to a URL and have the response returned to you as a byte[] using HttpClient.GetByteArrayAsync. With that binary content, you can read it into an Image using Image.FromStream.
Once you have that Image object, you can use the answer from here to do your cropping.
//Note: You only want a single HttpClient in your application
//and re-use it where possible to avoid socket exhaustion issues
using (var httpClient = new HttpClient())
{
//Issue the GET request to a URL and read the response into a
//stream that can be used to load the image
var imageContent = await httpClient.GetByteArrayAsync("<your image url>");
using (var imageBuffer = new MemoryStream(imageContent))
{
var image = Image.FromStream(imageBuffer);
//Do something with image
}
}
I am still very much learning ASP.NET using c# and Webmatrix. I have put together a photography competition site but can't quite find an ideal way of uploading images. I don't see the point of uploading images greater than 1200x900 (projectors maximum resolution) so want to make sure images are small as possible.
I am using tag and checking he image size. If it's too big I am using 'ImageResizer' to resize the image when saving. The only way I know to check the size is to convert the 'HttpPostedFileBase' file into an image using System.Drawing.Image. But when the image is 36Mpixels (it is a photography club) this is taking an age just to read the height and width properties. Can I just load the first x bytes to read the properties or do I have to read the whole image?
The second reason I am converting to an image is to extract the exif data. Again is there an easier and quicker way to read the exif data?
I hope my question makes sense this is all a bit new to me.
simplified code:
HttpPostedFileBase uploadedFile = Request.Files[0];
using (System.Drawing.Image image = System.Drawing.Image.FromStream(uploadedFile.InputStream, true, true))
{
string Exif;
System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
try{
Exif = encoding.GetString(image.GetPropertyItem(36867).Value);
}
catch
{
Exif="";
}
if (image.Width <Convert.ToInt32(MaxWidth) && image.Height <Convert.ToInt32(MaxHeight))
{
// SAVE IMAGE AS IS
image.Save(fileSavePath);
// LOAD IMAGE DETAILS WITH EXIF
db.Execute("INSERT INTO CompImages (ImageTitle,CompID,GroupID,ClubID,FileName,UserID,ExifDate) VALUES(#0,#1,#2,#3,#4,#5,#6)",ImageTitle,CompID,GroupID,ClubID,fileName,WebSecurity.CurrentUserId,DateTaken);
}
else
{
// LOAD IMAGE DETAILS WITH EXIF
db.Execute("INSERT INTO CompImages (ImageTitle,CompID,GroupID,ClubID,FileName,UserID,ExifDate) VALUES(#0,#1,#2,#3,#4,#5,#6)",ImageTitle,CompID,GroupID,ClubID,fileName,WebSecurity.CurrentUserId,DateTaken);
// RESIZE IMAGE
ImageResizer.ImageJob iF = new ImageResizer.ImageJob(image, "~/UpImages/"+CompID+"/"+fileName, new ImageResizer.ResizeSettings(
"width="+MaxWidth+";height="+MaxHeight+";format=jpg;mode=max"));
iF.CreateParentDirectory = true; //Auto-create the uploads directory.
iF.Build();
}
}
The only way I know to check the size is to convert the
'HttpPostedFileBase' file into an image using System.Drawing.Image.
You could also checkout the ContentLength property directly:
int uploadedFileSize = uploadedFile.ContentLength;
The second reason I am converting to an image is to extract the exif
data. Again is there an easier and quicker way to read the exif data?
I am not aware of a built-in class in the BCL that would allow you to read EXIF information without loading the image in memory but you could use some third party library like this one: http://www.codeproject.com/Articles/36342/ExifLib-A-Fast-Exif-Data-Extractor-for-NET-2-0
I have a imagestream in c# and i want to save them on the hard drive using the c# code. when i trying to do that i found Out of Memory whennever i have much enough Memory.
so i am sure that my code leak the resources so can someone show me how i can do that
HttpPostedFileBase file
file.SaveAs(location);
Image image = Image.FromFile(location,false);
image.Save(location, System.Drawing.Imaging.ImageFormat.Png);
image.fromFile line [3] caused Exception that out of Memory. can someone show me how i can do this in c#.
The file come from PNG using Ajax Request are come as octet type as Mime type so how i can do that.
Assuming you want to convert the image to PNG (otherwise there's no need to save the image once, reload it and re-save it again), it might be a good idea to avoid loading the image twice. See if something like this helps:
Image.FromStream(file.InputStream, false).Save(location, System.Drawing.Imaging.ImageFormat.Png);
file.SaveAs(location);
already saved the image at the given location or threw an exception, so the following lines are unnecessary.
Bitmap bmp = new Bitmap(file.InputStream);
bmp.Save(filename, ImageFormat.Png);
I'm very new to this stuff of saving images to the DB, and even when I thought it was very straight forward, it wasn't. What I'm trying to do is read and image file from the same computer in any format, display it in a picture box, and then convert the image to bytes to save it in the DB. Until now, I can display the image in the picture box, but I can't convert the image to bytes. Here's my code:
private void DisplayImage()
{
if (openFileDialog.ShowDialog(this) == DialogResult.OK)
{
try
{
Stream file;
if ((archivo = openFileDialog.OpenFile()) != null)
{
using (file)
{
pictureBox.Image = Image.FromStream(file);
}
}
}
catch (Exception ex)
{
...
}
}
}
That's a simple method that just displays the image in the picture box. The real problem is with the following method:
public static byte[] ConvertImageToBytes(Image image)
{
if (image != null)
{
MemoryStream ms = new MemoryStream();
using (ms)
{
image.Save(ms, ImageFormat.Bmp);
byte[] bytes = ms.ToArray();
return bytes;
}
}
else
{
return null;
}
}
When it tries to save the image to the memory stream, I get the error:
System.Runtime.InteropServices.ExternalException: A generic error occurred in GDI+.
Any ideas on what's happening?
You should use the RawFormat property of the original image as a parameter to the Save method, not default to a Bitmap. This will avoid image format type errors. eg:
image.Save(ms, image.RawFormat);
ms.Position = 0;
byte [] bytes=ms.ToArray();
I'd advise actually saving images to the file-system and simply storing the file path (preferably relative) in the database.
BLOBs (ie images etc) in a database cannot be indexed, are often stored in a secondary, slower access database area and will quickly blow out the size of the database (slower backups etc).
Cant you simply Read the file and load it to a byte[] using the File class:
byte[] imgData = System.IO.File.ReadAllBytes(#"C:\My Pic\Myfile.jpg");
You can pick the image path from your Open Dialog box.
That particular exception generally means that you are trying to save the image as the wrong format. In your code you specify ImageFormat.Bmp - is it actually a bitmap image, or did you perhaps load it from a JPEG or PNG? Attempting to save as a different format from the one you loaded will fail with ExternalException, as specified in the documentation.
Incidentally, I don't recommend storing images in a database and I believe most people here will agree. Databases may be able to handle this task but they are not optimized for it, and you end up hurting the performance of both your database and your application. Unless you are using SQL Server 2008 FILESTREAM columns, it is more efficient to store images on the file system.
It may be stupid to answer my own question, but I just found out that if I want to convert the Image object to bytes, I have to leave the original stream open. I saw this issue in another page I can't quite remember, and I tested it by leaving the stream open and it's true. So the format wasn't the problem. But I will take the advice of all of you and store the images in a separate directory. Thanks for your help guys!
The problem with this is that stream must be open during the lifetime of of the image otherwise will fail.
One solution that worked for me is just to create a copy of the image like this:
using (var ms = new MemoryStream(bytes))
{
_image = new Bitmap(Image.FromStream(ms));
}