简体   繁体   English

将图像从Bitmap上传到服务器为png

[英]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. 我正在尝试将我在C#winform应用程序中的System.Drawing.Bitmap变量上传为我的服务器上的.png图像。 Right now I know how to save a Bitmap as a .png file and then upload it to my server. 现在我知道如何将Bitmap保存为.png文件,然后将其上传到我的服务器。

//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 ? 我怎么能直接将Bitmap bitmap变量作为.png文件上传到我的服务器上,而不.png在本地保存为新的.png文件?

You could save the Bitmap to a stream and upload the stream: 您可以将Bitmap保存到流并上传流:

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());
}

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..
}

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. 由于该方法是UploadFile ,因此不能将文件的URL作为String作为第二个参数。

What I would suggest so the user doesn't see the PNG file if they don't have to... 我建议用户如果不需要PNG文件就看不到...

  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 使您的文件夹保存到此,其中%TEMP%是用户的临时文件夹,RandString是前面的随机字符串: %TEMP%\\RandString\\ImageName.jpg
  3. Save the file there and upload it. 将文件保存在那里并上传。
  4. When you're done, delete the folder %TEMP%\\RandString\\ . 完成后,删除文件夹%TEMP%\\RandString\\

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM