I have looked every where for my answer but couldn't find the right solution.Tried many solutions provided but still can't get it through.I uploaded an image in ftp server and i want it to get displayed into picture box in windows form without downloading it into local machine. Is it possible?
Please include complete code for the solution......
Here is a complete code: If any body needs.Make sure the image isn't large!!
public byte [] GetImgByte (string ftpFilePath)
{
WebClient ftpClient = new WebClient();
ftpClient.Credentials = new NetworkCredential(ftpUsername,ftpPassword);
byte[] imageByte = ftpClient.DownloadData(ftpFilePath);
return imageByte;
}
public static Bitmap ByteToImage(byte[] blob)
{
MemoryStream mStream = new MemoryStream();
byte[] pData = blob;
mStream.Write(pData, 0, Convert.ToInt32(pData.Length));
Bitmap bm = new Bitmap(mStream, false);
mStream.Dispose();
return bm;
}
You can use DownloadData to get a byte array and load that into the picturebox - see Download file directly to memory and How to put image in a picture box from a byte[] in C#
i've got some binary data which i want to save as an image. When i try to save the image, it throws an exception if the memory stream used to create the image, was closed before the save. The reason i do this is because i'm dynamically creating images and as such .. i need to use a memory stream.
this is the code:
[TestMethod]
public void TestMethod1()
{
// Grab the binary data.
byte[] data = File.ReadAllBytes("Chick.jpg");
// Read in the data but do not close, before using the stream.
Stream originalBinaryDataStream = new MemoryStream(data);
Bitmap image = new Bitmap(originalBinaryDataStream);
image.Save(#"c:\test.jpg");
originalBinaryDataStream.Dispose();
// Now lets use a nice dispose, etc...
Bitmap2 image2;
using (Stream originalBinaryDataStream2 = new MemoryStream(data))
{
image2 = new Bitmap(originalBinaryDataStream2);
}
image2.Save(#"C:\temp\pewpew.jpg"); // This throws the GDI+ exception.
}
Does anyone have any suggestions to how i could save an image with the stream closed? I cannot rely on the developers to remember to close the stream after the image is saved. In fact, the developer would have NO IDEA that the image was generated using a memory stream (because it happens in some other code, elsewhere).
I'm really confused :(
As it's a MemoryStream, you really don't need to close the stream - nothing bad will happen if you don't, although obviously it's good practice to dispose anything that's disposable anyway. (See this question for more on this.)
However, you should be disposing the Bitmap - and that will close the stream for you. Basically once you give the Bitmap constructor a stream, it "owns" the stream and you shouldn't close it. As the docs for that constructor say:
You must keep the stream open for the
lifetime of the Bitmap.
I can't find any docs promising to close the stream when you dispose the bitmap, but you should be able to verify that fairly easily.
A generic error occurred in GDI+.
May also result from incorrect save path!
Took me half a day to notice that.
So make sure that you have double checked the path to save the image as well.
Perhaps it is worth mentioning that if the C:\Temp directory does not exist, it will also throw this exception even if your stream is still existent.
Copy the Bitmap. You have to keep the stream open for the lifetime of the bitmap.
When drawing an image: System.Runtime.InteropServices.ExternalException: A generic error occurred in GDI
public static Image ToImage(this byte[] bytes)
{
using (var stream = new MemoryStream(bytes))
using (var image = Image.FromStream(stream, false, true))
{
return new Bitmap(image);
}
}
[Test]
public void ShouldCreateImageThatCanBeSavedWithoutOpenStream()
{
var imageBytes = File.ReadAllBytes("bitmap.bmp");
var image = imageBytes.ToImage();
image.Save("output.bmp");
}
I had the same problem but actually the cause was that the application didn't have permission to save files on C. When I changed to "D:\.." the picture has been saved.
You can try to create another copy of bitmap:
using (var memoryStream = new MemoryStream())
{
// write to memory stream here
memoryStream.Position = 0;
using (var bitmap = new Bitmap(memoryStream))
{
var bitmap2 = new Bitmap(bitmap);
return bitmap2;
}
}
This error occurred to me when I was trying from Citrix. The image folder was set to C:\ in the server, for which I do not have privilege. Once the image folder was moved to a shared drive, the error was gone.
A generic error occurred in GDI+. It can occur because of image storing paths issues,I got this error because my storing path is too long, I fixed this by first storing the image in a shortest path and move it to the correct location with long path handling techniques.
I was getting this error, because the automated test I was executing, was trying to store snapshots into a folder that didn't exist. After I created the folder, the error resolved
One strange solution which made my code to work.
Open the image in paint and save it as a new file with same format(.jpg). Now try with this new file and it works. It clearly explains you that the file might be corrupted in someway.
This can help only if your code has every other bugs fixed
It has also appeared with me when I was trying to save an image into path
C:\Program Files (x86)\some_directory
and the .exe wasn't executed to run as administrator, I hope this may help someone who has same issue too.
For me the code below crashed with A generic error occurred in GDI+on the line which Saves to a MemoryStream. The code was running on a web server and I resolved it by stopping and starting the Application Pool that was running the site.
Must have been some internal error in GDI+
private static string GetThumbnailImageAsBase64String(string path)
{
if (path == null || !File.Exists(path))
{
var log = ContainerResolver.Container.GetInstance<ILog>();
log.Info($"No file was found at path: {path}");
return null;
}
var width = LibraryItemFileSettings.Instance.ThumbnailImageWidth;
using (var image = Image.FromFile(path))
{
using (var thumbnail = image.GetThumbnailImage(width, width * image.Height / image.Width, null, IntPtr.Zero))
{
using (var memoryStream = new MemoryStream())
{
thumbnail.Save(memoryStream, ImageFormat.Png); // <= crash here
var bytes = new byte[memoryStream.Length];
memoryStream.Position = 0;
memoryStream.Read(bytes, 0, bytes.Length);
return Convert.ToBase64String(bytes, 0, bytes.Length);
}
}
}
}
I came across this error when I was trying a simple image editing in a WPF app.
Setting an Image element's Source to the bitmap prevents file saving.
Even setting Source=null doesn't seem to release the file.
Now I just never use the image as the Source of Image element, so I can overwrite after editing!
EDIT
After hearing about the CacheOption property(Thanks to #Nyerguds) I found the solution:
So instead of using the Bitmap constructor I must set the Uri after setting CacheOption BitmapCacheOption.OnLoad.(Image1 below is the Wpf Image element)
Instead of
Image1.Source = new BitmapImage(new Uri(filepath));
Use:
var image = new BitmapImage();
image.BeginInit();
image.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
image.CacheOption = BitmapCacheOption.OnLoad;
image.UriSource = new Uri(filepath);
image.EndInit();
Image1.Source = image;
See this: WPF Image Caching
Try this code:
static void Main(string[] args)
{
byte[] data = null;
string fullPath = #"c:\testimage.jpg";
using (MemoryStream ms = new MemoryStream())
using (Bitmap tmp = (Bitmap)Bitmap.FromFile(fullPath))
using (Bitmap bm = new Bitmap(tmp))
{
bm.SetResolution(96, 96);
using (EncoderParameters eps = new EncoderParameters(1))
{
eps.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 100L);
bm.Save(ms, GetEncoderInfo("image/jpeg"), eps);
}
data = ms.ToArray();
}
File.WriteAllBytes(fullPath, data);
}
private static ImageCodecInfo GetEncoderInfo(string mimeType)
{
ImageCodecInfo[] encoders = ImageCodecInfo.GetImageEncoders();
for (int j = 0; j < encoders.Length; ++j)
{
if (String.Equals(encoders[j].MimeType, mimeType, StringComparison.InvariantCultureIgnoreCase))
return encoders[j];
}
return null;
}
I used imageprocessor to resize images and one day I got "A generic error occurred in GDI+" exception.
After looked up a while I tried to recycle the application pool and bingo it works. So I note it here, hope it help ;)
Cheers
I was getting this error today on a server when the same code worked fine locally and on our DEV server but not on PRODUCTION. Rebooting the server resolved it.
public static byte[] SetImageToByte(Image img)
{
ImageConverter converter = new ImageConverter();
return (byte[])converter.ConvertTo(img, typeof(byte[]));
}
public static Bitmap SetByteToImage(byte[] blob)
{
MemoryStream mStream = new MemoryStream();
byte[] pData = blob;
mStream.Write(pData, 0, Convert.ToInt32(pData.Length));
Bitmap bm = new Bitmap(mStream, false);
mStream.Dispose();
return bm;
}
I writing a program that it can read .Dex file (Dexis X-ray image file) and convert it to jpg image. but i can't find out how to decode it.
i use this code to read and convert but the image is corrupt.
Read Image:
public static byte[] ImageToByte(string IMG_PATH)
{
byte[] img = null;
try
{
FileStream IM_STREAM = new FileStream(IMG_PATH, FileMode.Open, FileAccess.Read);
BinaryReader IM_BNR = new BinaryReader(IM_STREAM);
img = IM_BNR.ReadBytes((int)IM_STREAM.Length);
IM_BNR.Close();
IM_STREAM.Close();
}
catch (Exception ex)
{
StreamWriter swr = new StreamWriter("LOG.txt", true, Encoding.UTF8);
swr.WriteLine(ex.Message);
swr.Close();
}
return img;
}
Convert Image:
public static void SaveToFile(string path, byte[] b)
{
MemoryStream ms = new MemoryStream(b);
Image img = Image.FromStream(ms);
img.Save(path + "\\exam.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
img.Dispose();
}
The image before convert (.Dex, size 800x600px) -> after convert (.jpg, size 80x60). plz help me.
.dex is a semi-proprietary format. Using standard image decoding libraries the result you are seeing is the best you can do. If you are looking for a paid solution I know of a team that is currently working on a web services API for this but it hasn't been released publicly yet. If you'd be interested in being an early tester I can put you in touch.
I have the following function to get BitmapImage of file.
public static BitmapImage GetThumbnail(string filePath)
{
ShellFile shellFile = ShellFile.FromFilePath(filePath);
BitmapSource shellThumb = shellFile.Thumbnail.ExtraLargeBitmapSource;
BitmapImage bImg = new BitmapImage();
PngBitmapEncoder encoder = new PngBitmapEncoder();
MemoryStream memoryStream = new MemoryStream();
encoder.Frames.Add(BitmapFrame.Create(shellThumb));
encoder.Save(memoryStream);
bImg.BeginInit();
bImg.StreamSource = memoryStream;
bImg.EndInit();
return bImg;
}
When I get Video's Thumbnail it always works.
When I get Presentation (pptx) Thumbnail it doesn't work properly (I have no idea when it does and when it doesn't).
For example, I have 2 files in directory:
And this is how it looks in my program - 1 is ok and 1 isn't (sometimes both are ok, and sometimes both aren't):
I would appreciate if you could tell me what's the problem or maybe give me another way of getting the Thumbnail that will not fail...
p.s.
I would like to remind that with video files it works 100% fine (.mp3, .mp4, .wmv - thats what I tested)
Since I wanted to get pptx thumbnail, I came up with the following solution:
1. I extracted the thumbnail using DotNetZip
2. I got the thumbnail which is located in docProps directory
3. I extracted the thumbnail to memoryStream
4. I converted the memoryStream to BitmapImage and returned it.
here's the code:
public static BitmapImage GetPPTXThumbnail(string filePath)
{
using (ZipFile zip = ZipFile.Read(filePath))
{
ZipEntry e = zip["docProps/thumbnail.jpeg"];
BitmapImage bImg = new BitmapImage();
MemoryStream memoryStream = new MemoryStream();
bImg.BeginInit();
e.Extract(memoryStream);
memoryStream.Seek(0, SeekOrigin.Begin);
bImg.StreamSource = memoryStream;
bImg.EndInit();
return bImg;
}
}
Cant fail with this solution, this solution is only to get PPTX Thumbnail, I assume it works with all office xml files such as docx, xlsx, etc...
I have a wcf service which returns a bmp in byte[]. However Silverlight's Image control doesnt support displaying bmp's so i need to convert the bmp byte[] to png or jpg byte[]. Is there a library out there which does this conversion? Or any other way of displaying the bmp byte[] on the silverlight client?
Thanks!
Update1
In order to achieve the conversion I would have done something like this in .NET
private byte[] ConvertBmpToJpeg(byte[] bmp)
{
using (System.Drawing.Image image = System.Drawing.Image.FromStream(new MemoryStream(bmp)))
{
MemoryStream ms = new MemoryStream();
image.Save(ms, ImageFormat.Jpeg);
return ms.ToArray();
}
}
Since System.Drawing is not available in Silverlight, how do I achieve what the code does above in Silverlight?
Answer
using the library mentioned by dj kraze below-
ExtendedImage img = new ExtendedImage();
var bd = new BmpDecoder();
var je = new JpegEncoder();
bd.Decode(img, new MemoryStream(bitmapBytes));
MemoryStream ms = new MemoryStream();
je.Encode(img, ms);
BitmapImage bi = new BitmapImage();
bi.SetSource(new MemoryStream(ms.ToArray()));
display_ScreenShot.Source = bi;
Here is an even easier way of doing it..
This site may help out a lot
Image Converting