dimitris dimitris
dimitris dimitris

Reputation: 60

Upload image from Bitmap to server as png

I am trying to upload a System.Drawing.Bitmap variable I have in my C# winform application as a .png image on my server. Right now I know how to save a Bitmap as a .png file and then upload it to my server.

//Save bitmap variable as .png
bitmap.Save("img_1.png", ImageFormat.Png);

And then upload that to my server like so:

using (WebClient client = new WebClient())
{
    client.Credentials = new NetworkCredential("FTP_username",
        "FTP_password");
    client.UploadFile("ftp://100.100.100.100/new_folder/img_1.png",
        "img_1.png");
}

How could I upload the Bitmap bitmap variable as a .png file on my server directly, without having to save it as a new .png file locally first ?

Upvotes: 1

Views: 2277

Answers (3)

KinjalP
KinjalP

Reputation: 1

Try this:

using System.Drawing;

Bitmap b = (Bitmap)Bitmap.FromStream(file.InputStream);

using (MemoryStream ms = new MemoryStream()) {
    b.Save(ms, ImageFormat.Png);

    // use the memory stream to base64 encode..
}

Upvotes: 0

DDPWNAGE
DDPWNAGE

Reputation: 1443

You can't, due to the fact that the method is UploadFile, taking the URL of the file as a String as the second parameter.

What I would suggest so the user doesn't see the PNG file if they don't have to...

  1. Add a method that can generate and store a random string (like the one below) as a variable private to the class.
  2. Make your folder to save to this, where %TEMP% is the user's temporary folder and RandString is the random string from earlier: %TEMP%\RandString\ImageName.jpg
  3. Save the file there and upload it.
  4. When you're done, delete the folder %TEMP%\RandString\.

Upvotes: 0

DonBoitnott
DonBoitnott

Reputation: 11025

You could save the Bitmap to a stream and upload the stream:

using (WebClient client = new WebClient())
using (var ms = new MemoryStream())
{
    bitmap.Save(ms, ImageFormat.Png);
    client.Credentials = new NetworkCredential("FTP_username", "FTP_password");
    client.UploadData("ftp://100.100.100.100/new_folder/img_1.png", ms.ToArray());
}

Upvotes: 3

Related Questions