将图像从 Bitmap 以 png 格式上传到服务器
Upload image from Bitmap to server as png
我正在尝试将 C# winform 应用程序中的 System.Drawing.Bitmap
变量作为服务器上的 .png
图像上传。现在我知道如何将 Bitmap
保存为 .png
文件,然后将其上传到我的服务器。
//Save bitmap variable as .png
bitmap.Save("img_1.png", ImageFormat.Png);
然后像这样上传到我的服务器:
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");
}
我如何才能将 Bitmap bitmap
变量作为 .png
文件直接上传到我的服务器上,而不必先在本地将其另存为新的 .png
文件?
试试这个:
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..
}
您可以将 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());
}
不可以,因为这个方法是UploadFile
,把文件的URL当成String
作为第二个参数
我的建议是让用户在不需要时看不到 PNG 文件...
- 添加一个可以生成随机字符串(如下所示)并将其存储为 class.
私有变量的方法
- 将您的文件夹保存到此,其中 %TEMP% 是用户的临时文件夹,RandString 是之前的随机字符串:
%TEMP%\RandString\ImageName.jpg
- 将文件保存在那里并上传。
- 完成后,删除文件夹
%TEMP%\RandString\
。
我正在尝试将 C# winform 应用程序中的 System.Drawing.Bitmap
变量作为服务器上的 .png
图像上传。现在我知道如何将 Bitmap
保存为 .png
文件,然后将其上传到我的服务器。
//Save bitmap variable as .png
bitmap.Save("img_1.png", ImageFormat.Png);
然后像这样上传到我的服务器:
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");
}
我如何才能将 Bitmap bitmap
变量作为 .png
文件直接上传到我的服务器上,而不必先在本地将其另存为新的 .png
文件?
试试这个:
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..
}
您可以将 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());
}
不可以,因为这个方法是UploadFile
,把文件的URL当成String
作为第二个参数
我的建议是让用户在不需要时看不到 PNG 文件...
- 添加一个可以生成随机字符串(如下所示)并将其存储为 class. 私有变量的方法
- 将您的文件夹保存到此,其中 %TEMP% 是用户的临时文件夹,RandString 是之前的随机字符串:
%TEMP%\RandString\ImageName.jpg
- 将文件保存在那里并上传。
- 完成后,删除文件夹
%TEMP%\RandString\
。