[英]Upload png Image with ftp loose transparency
In my c# application, I'm trying to upload an png image using ftp, the problem is I loose transparency (the transparent area turn to black!). 在我的C#应用程序中,我尝试使用ftp上传png图像,问题是我失去了透明性(透明区域变成黑色!)。
PS : The image I send is stored in an Sql Server database, and they look fine in my application. PS:我发送的图像存储在Sql Server数据库中,它们在我的应用程序中看起来不错。 Here is the code I use : 这是我使用的代码:
private const int defultbuffersize = 1024 * 60;
public void UploadImage(Image image, string uri, string filename)
{
var request = WebRequest.Create(String.Format(@"{0}/{1}", uri, filename)) as FtpWebRequest;
if (request == null)
return;
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential("userName", "password");
request.UsePassive = true;
request.UseBinary = true;
request.KeepAlive = true;
using (var writer = request.GetRequestStream())
{
var bytesData = image.ToByteArray();
var position = 0;
while (position < bytesData.Length)
{
var buffer = readData(bytesData, position);
writer.Write(buffer, 0, buffer.Length);
position += buffer.Length;
}
}
}
private static byte[] readData(byte[] bytesData, int position)
{
var buffer = new byte[defultbuffersize];
var lenght = position + defultbuffersize > bytesData.Length ?
bytesData.Length - position : defultbuffersize;
Array.Copy(bytesData.ToArray(), position, buffer, 0, lenght);
return buffer;
}
Extension method in an other class 其他类中的扩展方法
public static byte[] ToByteArray(this Image image)
{
var stream = new MemoryStream();
image.Save(stream, ImageFormat.Jpeg);
return stream.ToArray();
}
Thanks in advance 提前致谢
The reason you lose transparency is found in your extension method 扩展方法中发现失去透明度的原因
public static byte[] ToByteArray(this Image image)
{
var stream = new MemoryStream();
image.Save(stream, ImageFormat.Jpeg);
return stream.ToArray();
}
You are trying to serialize an png image using jpeg format 您正在尝试使用jpeg格式序列化png图像
Change the extension method to this. 将扩展方法更改为此。
public static byte[] ToByteArray(this Image image)
{
var stream = new MemoryStream();
image.Save(stream, ImageFormat.Png);
return stream.ToArray();
}
This should fix your transparency problem. 这应该可以解决您的透明度问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.