我试图抓取旧网站上的大量图片,因为它很快就会被关闭。所有图像都是JPEG格式,所有图像都是从网站上下载的,但其中一些图像在我的本地(Windows)计算机上以绿色 - 粉红色的重音显示。
我发现没有任何损坏的图片有色彩空间元数据和嵌入的颜色配置文件,但我不确定这是不是问题,因为我不熟悉图像处理。我无法在C#中找到任何设置来将颜色配置文件设置为RGB或类似的东西。 这是我的代码:
private static Image GetImageFromUrl(string url)
{
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
try
{
using (HttpWebResponse httpWebReponse = (HttpWebResponse)httpWebRequest.GetResponse())
{
using (Stream stream = httpWebReponse.GetResponseStream())
{
return Image.FromStream(stream);
}
}
}
catch (WebException e)
{
return null;
}
}
private static void SaveImage(string folderName, string fileName, Image img)
{
if (img == null || folderName == null || folderName.Length == 0)
{
return;
}
string path = "D:\\Files\\" + folderName;
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
using (img)
{
img.Save("D:\\Files\\" + folderName + "\\" + fileName, ImageFormat.Jpeg);
}
}
SaveImage(folderName, fileName, GetImageFromUrl(resultUrl));
这是图片在浏览器中的样子(左)以及使用此程序下载时(右图):
感谢您的帮助。
答案 0 :(得分:2)
好的,似乎可以通过直接保存文件流而不将其转换为本地计算机上的Image
对象来绕过此问题。损坏的调色板仍然存在,但不知何故,Windows图片查看器能够正确显示保存的图像(没有奇怪的颜色重音),Photoshop等也是如此。
正如Jason Watkins在评论中所建议的,我的代码现在看起来像这样:
private static void SaveImageFromUrl(string folderName, string fileName, string url)
{
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
try
{
using (HttpWebResponse httpWebReponse = (HttpWebResponse)httpWebRequest.GetResponse())
{
using (Stream stream = httpWebReponse.GetResponseStream())
{
//need to call this method here, since the image stream is not disposed
SaveImage(folderName, fileName, stream);
}
}
}
catch (WebException e)
{
Console.WriteLine("Image with URL " + url + " not found." + e.Message);
}
}
private static void SaveImage(string folderName, string fileName, Stream img)
{
if (img == null || folderName == null || folderName.Length == 0)
{
return;
}
string path = "D:\\Files\\" + folderName;
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
using (var fileStream = File.Create("D:\\Files\\" + folderName + "\\" + fileName))
{
img.CopyTo(fileStream);
//close the stream from the calling method
img.Close();
}
}
SaveImageFromUrl(folderName, fileName, resultUrl);