'In Selenium c#, how to bypass image validation if the picture is not accessible (404 image not found)?
I have image validation code that checks whether or not a picture is empty. We don't have images in many places in my project.
So I'd want to ignore any images that produce a 404 response code and only look at images that return a 200 acceptable response code.
In this case, I'd want some support or assistance.
Code:
**return GetImage(src).IsEmpty();**
public static Bitmap GetImage(string url)
{
byte[] imageData = HttpHelper.downloadData(Randomize(url)); //DownloadData function from here
if (imageData != null)
{
var stream = new MemoryStream(imageData);
var img2 = new Bitmap(System.Drawing.Image.FromStream(stream));
stream.Close();
return img2;
}
else
return null;
}
public static byte[] downloadData(string url)
{
downloadedData = new byte[0];
try
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
//HttpRequestCachePolicy noCachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore);
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.UserAgent = "Test";
//req.CachePolicy = noCachePolicy;
WebResponse response = req.GetResponse();
Stream stream = response.GetResponseStream();
byte[] buffer = new byte[1024];
int dataLength = (int)response.ContentLength;
MemoryStream memStream = new MemoryStream();
while (true)
{
int bytesRead = stream.Read(buffer, 0, buffer.Length);
if (bytesRead == 0)
{
Application.DoEvents();
break;
}
else
{
memStream.Write(buffer, 0, bytesRead);
}
}
downloadedData = memStream.ToArray();
stream.Close();
memStream.Close();
}
catch (Exception ex)
{
return null;
}
return downloadedData;
}
public static bool IsEmpty(this Bitmap image)
{
if (image == null)
return true;
var data = image.LockBits(new Rectangle(0, 0, image.Width, image.Height),
ImageLockMode.ReadOnly, image.PixelFormat);
var bytes = new byte[data.Height * data.Stride];
Marshal.Copy(data.Scan0, bytes, 0, bytes.Length);
image.UnlockBits(data);
return bytes.All(x => x == 0);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
