So here's the deal, I have to take a text value from sql server, that beeing a encoded image, store it in a string and then I can convert it to Image type by decoding it, the thing is, how do I display said decoded image in the asp:image thing? cuz i whas hopping that this component would have an .image property where i can just put the image and it would display it just like that but it just has .ImageUrl that would work just fine if the image was stored in my pc but it isnĀ“t, I tried to make it a binary string and then instead of using and asp:image use img, then put the decoded image in .src by converting it to a base 64 string but i've been told that it only works with .jpg format and i have to use both .jpg and .png,
I'm new in asp.net so I may be making a dumb question but I search everywhere and I can't seem to find a clear solution, can somebody help me?
btw sorry if I'm barely understandable, English isn't my main language.
byte[] imageArray = System.IO.File.ReadAllBytes(Server.MapPath("~/App_Data/Images/client_group_logo.png"));
var imageString = imageArray != null ? Convert.ToBase64String(imageArray) : "";
var img = string.Format("data:image/jpg;base64,{0}", imageString);
ViewBag.ImagePath = img;
if you view this image.please paste this below code in your cshtml file.
<img src="#Url.Content(ViewBag.ImagePath)" />
Related
I'm getting a Base64String from an API (Stable Horde)
I tried using
filePath = some path + image.png
File.WriteAllBytes(filePath, Convert.FromBase64String(myImageData.generations[0].img));
This does create an image on the hard drive but its not really a png image so when I try to read all bytes
back into an image in the scene there is a problem. Doesn't work. I figured out that this is because it was not encoded correctly into a real png in the first place.
I'm trying to translate this python code (into Unity C#) that does create an actual png:
b64img = results[iter]["img"]
base64_bytes = b64img.encode('utf-8')
img_bytes = base64.b64decode(base64_bytes)
img = Image.open(BytesIO(img_bytes))
if len(results) > 1:
final_filename = f"{iter}_{filename}"
img.save(final_filename)
I've been trying solutions searching online for about 16 hours with no luck. Can't believe how poorly documented and hard to do this is?
Can anyone help? What's the correct way to take a Base64String and convert it to a png in Unity C#.
Thanks!
Try this:
string base64String = "(your base64 string)";
byte[] data = System.Convert.FromBase64String(base64String);
Texture2D texture = new Texture2D(0, 0);
ImageConversion.LoadImage(texture, data);
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 image/jped base64 code like this,
data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAA......
I need, convert to image this code and save file as jpeg file. And I figured the Windows Form (C#). Insert to Textbox and button. Insert the base 64 code (the code is above) in textbox and click the button.
private void button1_Click(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(textBox1.Text))
{
string imageDataParsed = textBox1.Text.Substring(textBox1.Text.IndexOf(',') + 1);
byte[] imageBytes = Convert.FromBase64String(imageDataParsed);
MemoryStream ms1 = new MemoryStream(imageBytes);
Image img = Image.FromStream(ms1);
img.Save(Application.StartupPath + "\\Images\\1.jpg", ImageFormat.Jpeg);
}
}
File save as a jpeg. But this file seems like this on Windows Photo Viewer
But when I run on the Google Chrome this base 64 code, there is no problem. Viewing nice on Google Chrome browser.
Summary my question, I need base64 code to Image and save this file my server as jpeg file.
How can i solve this problem?
Thanks.
Convert Base64 straight to file avoid loading it into a Image, this way it should be all in-tact like the original image, of course this still doesn't solve your image showing problem.
byte[] newfile = Convert.FromBase64String(data);
File.WriteAllBytes(#"C:\path\to\file.jpg", newfile);
i think the problem is big endian and little endian mismatch see http://en.wikipedia.org/wiki/Endianness
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 to display an image,which is in base64 string format. It's working fine in ie9,chrome and mozilla.But when using ie8 image is not completly displaying.Due to security purpose i am not able save image on server and user url for displaying image.Is there any other way to display image on ie8.
As per the answer from Ryan McGrath at Internet Explorer and Base64 image display: IE8 can only show Base64 images up to 32KB in size.
Most likely your image is too large to be handled by IE8.
I don't have the time to write an extensive example right now, but a possible workaround would be to serve the image through another webpage. Read the image into a stream and send it back. For example, you might do something like this:
void GetImage(int imageId) {
byte[] imageData = GetDataFromDatabase(imageId);
using (MemoryStream ms = new MemoryStream(imageData)) {
Response.ContentType = "image/png";
ms.WriteTo(Response.OutputStream);
}
}
And then in your webpage you could do something like this:
<img src="Image.aspx?GetImage&imageId=1"/>
Note: All of the this is non-working code and possibly contains typos and non-existing methods. But it's just an idea to get you started. If you perform a Google search for "C# + asp.net output image" you get a whole bunch of results with working code samples, such as http://www.codeproject.com/Articles/33310/C-Save-and-Load-Image-from-Database.