failed to convert byte array into image in some certain browser - c#

i am using Visual studio 2010 with .Net 3.5 framework
my code work fine in my windows 8, IE 9
however it doesnt work in windows xp , IE7, i have no idea what is exactly happen
Byte[] byImg = ((byte[])dr["logo"]);
var vBase64String = Convert.ToBase64String(byImg);
logo.ImageUrl = string.Format("data:image/gif;base64,{0}", vBase64String);
is there any support issue?

IE7 does not support data: protocol for images. It is implemented in IE8 and above.
If you need to support IE7 - server separate image files instead.

Try this:
string imageDataParsed = imageData.Substring( imageData.IndexOf( ',' ) + 1 );
byte[] imageBytes = Convert.FromBase64String( imageDataParsed );
using ( var imageStream = new MemoryStream( imageBytes, false ) )
{
Bitmap image = new Bitmap( imageStream );
}

Related

OutOfMemoryException using Bitmap to resize large image

I want to resize the image in my website, but when I using Bitmap to load a image of 14032*19864(png extension), an OutOfMemoryException is thrown. My compiler configuration is any cpu.
I was doubting whether the running environment is x64.
the code is below:
public ActionResult BimDWGViewer()
{
Viewer.Uri uri = null;
string url = Request.Params["u"];
uri = new Viewer.Uri("image#"+url);
int width = Int32.Parse(Request.Params["w"]);
int height = Int32.Parse(Request.Params["h"]);
Nebula.Nexus.Helpers.ModelUriTranslator.TranslateUri(uri);
if (uri.IsFileProtocol)
{
string path = uri.Path;
System.Drawing.Bitmap image_source = new System.Drawing.Bitmap(path);
System.Drawing.Bitmap image_result = new System.Drawing.Bitmap(width,height);
using (System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(image_result))
{
g.DrawImage(image_source, new System.Drawing.Rectangle(0, 0, width, height), new System.Drawing.Rectangle(0, 0, image_source.Width, image_source.Height), System.Drawing.GraphicsUnit.Pixel);
}
MemoryStream output = new MemoryStream();
image_result.Save(output, System.Drawing.Imaging.ImageFormat.Png);
byte[] res = output.ToArray();
output.Dispose();
image_source.Dispose();
image_result.Dispose();
return new FileContentResult(res, "image/png");
}
}
The exception occurs in the line of
System.Drawing.Bitmap image_source = new System.Drawing.Bitmap(path);
Make sure you have the gcAllowVeryLargeObjects element set to true in your config file.
There's a 2 GB max for individual allocations in .NET (even when running as a 64-bit process) and it's very possible that one of the classes you're using is doing something internally that bumps into this limit. It's a pretty common problem, and fixing your config file should get you around it.
Update: Per the comments below, the problem that #majing ran into was that Visual Studio was launching his web app in a 32-bit edition of IIS Express. Configuring VS to launch IIS as a 64-bit process fixed the issue.
Have you disabled "Prefer 32 bit"?
See http://www.neovolve.com/2015/07/31/disable-prefer-32-bit/

Converting a BitmapImage byte array to an Image byte array (WinRT -> WinForms)

I have 2 solutions in this project. A windows forms solution and a Windows 8.1 Tablet project.
This is what's supposed to happen:
User takes a picture using the tablet and uploads it to a MySQL database in the form of a byte array.
User starts up the windows forms application and loads the byte array from the MySQL database.
It then converts the byte array to an image which is placed in a picturebox.
I'm storing the byte array like this:
CameraCaptureUI dialog = new CameraCaptureUI();
dialog.PhotoSettings.Format = CameraCaptureUIPhotoFormat.Jpeg;
Size aspectRatio = new Size(16, 9);
dialog.PhotoSettings.CroppedAspectRatio = aspectRatio;
StorageFile file = await dialog.CaptureFileAsync(CameraCaptureUIMode.Photo);
if (file != null)
{
BitmapImage bitmapImage = new BitmapImage();
using (IRandomAccessStream fileStream = await file.OpenAsync(FileAccessMode.Read))
{
var readStream = fileStream.AsStreamForRead();
byte[] pixeBuffer = new byte[readStream.Length];
await readStream.ReadAsync(pixeBuffer, 0, pixeBuffer.Length);
}
The byte array is successfully stored in my database.
I'm running into a problem when converting the byte array into a WinForms Image.
This is my code:
using (var ms = new MemoryStream(bytes))
{
Image i = Image.FromStream(ms);
return i;
}
This gives me an invalid parameter exception.
I'm guessing it's something with the image format? I'm really new to streams though so I have no idea.
Any help is welcome!
PS: I know storing in the SQL database runs perfectly since I can store and load images perfectly using the WinForms application only.
Have you tried setting the position of the MemoryStream back to the beginning before trying to create the Image...
ms.Seek(0, SeekOrigin.Begin);
using (MemoryStream ms = new MemoryStream())
{
WriteableBitmap btmMap = new WriteableBitmap
(bitmapImage.PixelWidth, bitmapImage.PixelHeight);
return ms.ToArray();
}
Try it ,
it's working with me

Windows Phone 8 Save Image from byte[]

I have created a basic steganography application for windows phone 8 that works fine on the emulator but I get an error when using a device. With the emulator I can save a byte[] as an image as shown below:
byteArrayTextandImage = EncodeText(byteArrayInputImageEncode,byteArrayInputText, 4096);
using (var s = new MemoryStream())
{
Picture pic = library.SavePicture(Guid.NewGuid().ToString(), byteArrayTextandImage);
}
I tried to get around it by using a WritableBitmap as shown below:
using (var s = new MemoryStream())
{
WriteableBitmap wb = new WriteableBitmap((BitmapSource)bmp);
wb.SaveJpeg(s, bmp.PixelWidth, bmp.PixelHeight, 0, 72);
s.Seek(0, SeekOrigin.Begin);
var pic = library.SavePicture(Guid.NewGuid().ToString() + ".jpg", s);
MessageBox.Show(pic.Name);
}
however this is modifying the image and removing the text I had encoded within it. Has anybody encountered a problem like this before? Why would the emulator work fine but not on a device? I have checked the manifest and I have the necessary capabilities checked.
Thanks for any help anybody can provide.

BinaryFormatter.Serialize( Image ) - ExternalException - A generic error occurred in GDI+

When I try to Serialize some images using the BinaryFormatter, I'll get a ExternalException - A generic error occurred in GDI+." After scratching my head for awhile, I decided to create a simple test project to narrow down the problem:
static void Main(string[] args)
{
string file = #"C:\temp\delme.jpg";
//Image i = new Bitmap(file);
//using(FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read))
byte[] data = File.ReadAllBytes(file);
using(MemoryStream originalms = new MemoryStream(data))
{
using (Image i = Image.FromStream(originalms))
{
BinaryFormatter bf = new BinaryFormatter();
using (MemoryStream ms = new MemoryStream())
{
// Throws ExternalException on Windows 7, not Windows XP
bf.Serialize(ms, i);
}
}
}
}
For specific images, I've tried all sorts of ways of loading the image and I could not get it to work under Windows 7, even when running the program as Administrator.
I've copied the exact same executable and image into my Windows XP VMWare instance and I have no problems.
Anyone have any idea of why for some images it doesn't work under Windows 7, but works under XP?
Here's one of the images:
http://www.2shared.com/file/7wAXL88i/SO_testimage.html
delme.jpg md5: 3d7e832db108de35400edc28142a8281
As the OP pointed out, the code provided throws an exception that seems to be occurring only with the image he provided but works fine with other images on my machine.
Option 1
static void Main(string[] args)
{
string file = #"C:\Users\Public\Pictures\delme.jpg";
byte[] data = File.ReadAllBytes(file);
using (MemoryStream originalms = new MemoryStream(data))
{
using (Image i = Image.FromStream(originalms))
{
BinaryFormatter bf = new BinaryFormatter();
using (MemoryStream ms = new MemoryStream())
{
// Throws ExternalException on Windows 7, not Windows XP
//bf.Serialize(ms, i);
i.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp); // Works
i.Save(ms, System.Drawing.Imaging.ImageFormat.Png); // Works
i.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); // Fails
}
}
}
}
It could be that the image in question was created with a tool that added some additional information that is interfering with the JPEG serialization.
P.S. The image can be saved to memory stream using BMP or PNG format. If changing the format is an option, then you can try out either of these or any other format defined in ImageFormat.
Option 2
If your goal is just to get the contents of the image file into a memory stream, then doing just the following would help
static void Main(string[] args)
{
string file = #"C:\Users\Public\Pictures\delme.jpg";
using (FileStream fileStream = File.OpenRead(file))
{
MemoryStream memStream = new MemoryStream();
memStream.SetLength(fileStream.Length);
fileStream.Read(memStream.GetBuffer(), 0, (int)fileStream.Length);
}
}
Although the Bitmap class is marked as [Serializable], it does not actually support serialisation. The best you can do is serialise the byte[] containing the raw image data and then re-create it using a MemoryStream and the Image.FromStream() method.
I can't explain the inconsistent behaviour you're experiencing; for me, it fails unconditionally (although I first discovered this when trying to marshal images between different app domains, rather than manually serialising them).
I don't know for sure but I would lean towards different security models for XP vs Windows 7. Image inherits from System.MarshalByRefObject. There is probably proxying going on between application domains when serialization is performed. This proxying might be forbidden in Windows 7.
http://msdn.microsoft.com/en-us/library/system.marshalbyrefobject%28v=vs.71%29.aspx

Read Base64 image with C# in a Windows 8 app

I'm trying to display an image on a Windows 8 app. The image data is gathered from a web service, and provided as a Base64 encoded string.
I found the following on Stack Overflow:
How do i read a base64 image in WPF?
However, when I come to use the BitmapImage Class, I can't seem to access System.Windows.Media.Imaging, even though the following Microsoft documentation leads us to believe that it is available for use in .NET 4.5, and with Windows 8 apps:
http://msdn.microsoft.com/en-us/library/ms619218.aspx
Many thanks for your help.
The classes you want are in the Windows.UI.Xaml.Media.Imaging namespace. Here is an example of taking a Base64 image and creating an image out of it ...
var img = #"/9j/4AAQSkZJRgABAQAAAQABAAD//gA7Q1JFQ ... "; // Full Base64 image as string here
var imgBytes = Convert.FromBase64String(img);
var ms = new InMemoryRandomAccessStream();
var dw = new Windows.Storage.Streams.DataWriter(ms);
dw.WriteBytes(imgBytes);
await dw.StoreAsync();
ms.Seek(0);
var bm = new BitmapImage();
bm.SetSource(ms);
// img1 is an Image Control in XAML
bm.ImageOpened += (s, e) => { this.img1.Source = bm; };
bm.ImageFailed += (s, e) => { Debug.WriteLine(e.ErrorMessage); };
I could not copy a full Base64 image into the answer.

Categories

Resources