使用webClient保存网络驱动器照片

时间:2016-02-22 15:44:46

标签: c# vb.net bitmap base64 webclient

嘿所有我有以下VB.net代码,我需要转换为C#:

 Dim tClient As WebClient = New WebClient
 Dim imgLink As String = "\\the\path\photos\" + userID + ".jpg"
 Dim tImage As Bitmap = Bitmap.FromStream(New MemoryStream(tClient.DownloadData(imgLink)))

 Dim mImage As String = ImageToBase64(tImage, System.Drawing.Imaging.ImageFormat.Jpeg)

在VB中工作得很好,但是当我尝试将其转换为C#:

WebClient tClient = new WebClient();
string mImage = @"\\the\path\photos\" + userID + ".jpg";
Bitmap tImage = Bitmap.FromStream[new MemoryStream[tClient.DownloadData(mImage)]];

mImage = ImageToBase64(tImage, System.Drawing.Imaging.ImageFormat.Jpeg);

tClient.DownloadData(imagePath)上有错误说:

  

错误7无法隐式转换类型' byte []'到' int'

在C#中定义它的正确方法是什么?

2 个答案:

答案 0 :(得分:3)

还有一些问题:

  • 您已将数组运算符括号[与Bitmap.FromStream和MemoryStream构造函数中的函数调用(括号混淆
  • 您一次只下载整个文件,只是将其加载到流中 - 这无法实现流式传输
  • Bitmap.FromStream实际上来自它的超类Image,并返回一个Image(你不能保证文件将是一个实际的位图,而不是其他格式 - 如果你确定它,你必须把它强制转换为Bitmap)

试试这个:

WebClient tClient = new WebClient();
string mImage = @"\\the\path\photos\" + userID + ".jpg";
Bitmap tImage = (Bitmap)Bitmap.FromStream(tClient.OpenRead(mImage));

mImage = ImageToBase64(tImage, System.Drawing.Imaging.ImageFormat.Jpeg);

WebClient.OpenRead返回一个你可以直接传递来构建图像的流(不将所有数据都拉到字节数组中)

答案 1 :(得分:1)

请勿使用方括号。但是使用括号并声明new Bitmap

WebClient tClient = new WebClient();
string mImage = @"\\the\path\photos\" + userID + ".jpg";
Bitmap tImage = new Bitmap(Bitmap.FromStream(new MemoryStream(tClient.DownloadData(mImage))));

请注意,convert the image to base 64需要byte[],您可以从tClient.DownloadData(mImage)

获取mImage = Convert.ToBase64String(tClient.DownloadData(mImage));
 $(document).ready(function(){
resizeDiv();
});

window.onresize = function(event) {
resizeDiv();
}

function resizeDiv() {
vpw = $(window).width();
vph = $(window).height();
$('#somediv').css({'height': vph + 'px'});
}