Upload a System.Drawing.Bitmap without saving to disk first - c#

I have a System.Drawing.Bitmap which needs to uploaded to a server, all this is working fine except I'm writing the image to disk, uploading the image on disk, then finally deleting it. Is there a way to do this without saving to disk first and upload it from memory? The code I'm currently using looks something like this.
System.Drawing.Bitmap bmp = new Bitmap(someX, someY);
//code to create my image
bmp.Save("c:\sometempfile.jpeg", System.Drawing.Imaging.ImageFormat.Jpeg);
WebClient webClient = new WebClient();
webClient.UploadFile(urlToUploadTo, "POST", "c:\sometempfile.jpeg");
System.IO.File.Delete("c:\sometempfile.jpeg");

You can try something like this. I haven't tested it, so that's up to you, but basically you should write the bitmap to a memorystream, after which you can write that stream to your webclient's target URL via the desired HTTP method.
using (var client = new WebClient())
{
MemoryStream memoryStream = new MemoryStream();
bmp.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Jpeg);
memoryStream.Seek(0, System.IO.SeekOrigin.Begin);
using (var postStream = client.OpenWrite(endpointUrl))
{
memoryStream.CopyTo(postStream);
}
}

Related

Google drive upload an image from memory stream

Good day,
I have this code which upload an image to Google drive from file, everything works well:
// Create a new file on Google Drive
using (var fsSource = new FileStream(UploadFileName, FileMode.Open, FileAccess.Read))
{
// Create a new file, with metadata and stream.
var request = service.Files.Create(fileMetadata, fsSource, "image/jpg");
request.Fields = "*";
var results = await request.UploadAsync(CancellationToken.None);
}
Now I want to do some image manipulation before uploading so that I could convert the image to jpeg if the image is in another format (png or bmp for example) or resize the image, so I changed the file to stream for manipulation, I don't want to save it locally again because the code could be used on a website on mobiles, that's why I am saving to stream.
using (MemoryStream ms = new MemoryStream())
{
Image img = Image.FromFile(uploadfileName);
img.Save(ms, ImageFormat.Jpeg);
}
How can I now upload this ms stream to Google Drive?
Thanks for any clue, I'm not an expect in field.
Thanks all for assistance.
The answer suggested by canton7 works:
Just set ms.Position = 0, so that the next read starts reading from the beginning of the stream, then use it in place of your fsSource in your first snippet

ExternalException when saving .bmp to MemoryStream as .png

I'm converting a batch of .bmp's to .png. This is the relevant part of the code:
foreach (string path in files) {
using (fs = new FileStream(path, FileMode.Open)) bmp = new Bitmap(fs);
using (ms = new MemoryStream()) {
bmp.Save(ms, ImageFormat.Png);
bmp.Dispose();
png = Image.FromStream(ms);
}
png.Save(path);
}
At the line bmp.Save(ms, ImageFormat.Png); the following exception is thrown:
System.Runtime.InteropServices.ExternalException: 'A generic error occurred in GDI+.'
According to MSDN this means the image was either saved with the wrong format or to the same location it was read from. The latter is not the case. However, I don't see how I gave it the wrong format: on the same MSDN page an example is given where a .bmp is converted to a .gif in the same manner.
Does it have to do with me saving to a MemoryStream? This is done so that I can overwrite the original file with the converted one. (Note that the .bmp suffix is kept intentionally. This shouldn't be the problem, since the exception appears before the final file is saved.)
In the MSDN documentation of that Bitmap constructor it says:
You must keep the stream open for the lifetime of the Bitmap.
and that same remark can be found on Image.FromStream.
So your code should carefully handle the scope and lifetime of the streams it uses for each of those bitmaps/images.
Combining all that the following code handles those streams correctly:
foreach (string path in files) {
using (var ms = new MemoryStream()) //keep stream around
{
using (var fs = new FileStream(path, FileMode.Open)) // keep file around
{
// create and save bitmap to memorystream
using(var bmp = new Bitmap(fs))
{
bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
}
}
// write the PNG back to the same file from the memorystream
using(var png = Image.FromStream(ms))
{
png.Save(path);
}
}
}

How to upload a large file (1 GB +) to Google Drive using GoogleDrive REST API

I am tying to upload large files(1 GB+) to Google Drive using GoogleDrive API. My code works fine with smaller files. But when it comes to larger files error occurs.
Error occurs in the code part where the the file is converted into byte[].
byte[] data = System.IO.File.ReadAllBytes(filepath);
Out of memory exception is thrown here.
Probably you followed developers.google suggestions and you are doing this
byte[] byteArray = System.IO.File.ReadAllBytes(filename);
MemoryStream stream = new MemoryStream(byteArray);
try {
FilesResource.InsertMediaUpload request = service.Files.Insert(body, stream, mimeType);
request.Upload();
I have no idea why the suggest to put the whole file in a byte array and then create a MemoryStream on it.
I think that a better way is this:
using(var stream = new System.IO.FileStream(filename,
System.IO.FileMode.Open,
System.IO.FileAccess.Read))
{
try
{
FilesResource.InsertMediaUpload request = service.Files.Insert(body, stream, mimeType);
request.Upload();
.
.
.
}

C#: Getting Error: "A generic error occurred in GDI+" When trying to copy imagebox.Image into memory stream. This stream is not being saved to file.

I am getting an odd error with Image.save(Stream, Format).
I tried looking around on here for a solution but everyone seems to think the error is from file permissions. That can't be it in my case case the Stream isn't going into a file. My code is below:
MemoryStream Stream = new MemoryStream();
this.Image_Box_1.Image.Save(Stream, System.Drawing.Imaging.ImageFormat.Jpeg);
TI.AlbumCover = Stream.ToArray();
Stream.Close();
TI.AlbumCover is a byte[].
Does anyone have any ideas on what the problem might be?
EDIT:
Ok, so I worked it out. The original file could sometimes come from a jpg file, sometimes from a byte array (part of an id3 tag). The problem was that when the image came from the file, I was closing the stream after creating the image box image. While the image remained visible, the data was no longer available.
Since I also later needed to overwrite that jpg file, I could not simply leave the filestream for it open so I left the rest of my code the same and changed the code to read from the jpg to the following:
FileStream FS = new FileStream(File, FileMode.Open, FileAccess.Read);//Read in the jpg file
Image IMG = Image.FromStream(FS);//Create an image from the file data
MemoryStream MS = new MemoryStream();
IMG.Save(MS, System.Drawing.Imaging.ImageFormat.Jpeg);//Save the image data to a memory stream
byte[] temp = MS.ToArray();//Copy the image data to a byte array
//close the streams
MS.Close();
FS.Close();
return temp; //was originally returning an image
Then after executing this code I change the code that placed the image into the image box to:
try
{
if (this.m_V2Tag.AlbumCover != null)
this.Image_Box_1.Image = Image.FromStream(new MemoryStream(this.m_V2Tag.AlbumCover));
//changed code
else
{
MemoryStream temp = new MemoryStream(this.getFolderJpg()); //create a memory stream from the byte[]. This stream can safely be left open.
this.Image_Box_1.Image = Image.FromStream(temp); // create image and assign it to the image box
}
}
catch
{
this.Image_Box_1.Image = null;
}

Load a byte[] into an Image at Runtime

I have a byte[] that is represented by an Image. I am downloading this Image via a WebClient. When the WebClient has downloaded the picture and I reference it using its URL, I get a byte[]. My question is, how do I load a byte[] into an Image element in WPF? Thank you.
Note: This is complementary to the question I asked here: Generate Image at Runtime. I cannot seem to get that approach to work, so I am trying a different approach.
Create a BitmapImage from the MemoryStream as below:
MemoryStream byteStream = new MemoryStream(bytes);
BitmapImage image = new BitmapImage();
image.BeginInit();
image.StreamSource = byteStream;
image.EndInit();
And in XAML you can create an Image control and set the above image as the Source property.
You can use a BitmapImage, and sets its StreamSource to a stream containing the binary data. If you want to make a stream from a byte[], use a MemoryStream:
MemoryStream stream = new MemoryStream(bytes);
In .Net framework 4.0
using System.Drawing;
using System.Web;
private Image GetImageFile(HttpPostedFileBase postedFile)
{
if (postedFile == null) return null;
return Image.FromStream(postedFile.InputStream);
}
One way that I figured out how to do it so that it was both fast and thread safe was the following:
var imgBytes = value as byte[];
if (imgBytes == null)
return null;
using (var stream = new MemoryStream(imgBytes))
return BitmapFrame.Create(stream,BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
I threw that into a converter for my WPF application after running the images as Varbinary from the DB.

Categories

Resources