I have a hyperlink which has a image.
I need to read/load the image from that hyperlink and assign it to a byte array (byte[]
) in C#.
Thanks.
URL url = new URL(imagePath); ByteArrayOutputStream output = new ByteArrayOutputStream(); URLConnection conn = url. openConnection(); conn. setRequestProperty("User-Agent", "Firefox"); try (InputStream inputStream = conn. getInputStream()) { int n = 0; byte[] buffer = new byte[1024]; while (-1 !=
Read the image using the read() method of the ImageIO class. Create a ByteArrayOutputStream object. Write the image to the ByteArrayOutputStream object created above using the write() method of the ImageIO class. Finally convert the contents of the ByteArrayOutputStream to a byte array using the toByteArray() method.
A byte array is just a collection of bytes. Theoretically, the contents of the byte array would be the same as what you'd see if you used a HEX editor to view the bytes of the corresponding image as saved on the disk.
A byte array is simply a collection of bytes. The bytearray() method returns a bytearray object, which is an array of the specified bytes. The bytearray class is a mutable array of numbers ranging from 0 to 256.
WebClient.DownloadData is the easiest way.
var webClient = new WebClient(); byte[] imageBytes = webClient.DownloadData("http://www.google.com/images/logos/ps_logo2.png");
Third party edit: Please note that WebClient is disposable, so you should use using
:
string someUrl = "http://www.google.com/images/logos/ps_logo2.png"; using (var webClient = new WebClient()) { byte[] imageBytes = webClient.DownloadData(someUrl); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With