Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Image to byte array from a url

Tags:

c#

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.

like image 825
Sharpeye500 Avatar asked Jan 05 '11 00:01

Sharpeye500


People also ask

How do you turn a URL into a byte?

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 !=

How can I get byte array from image?

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.

How is an image stored in a byte array?

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.

What is Bytearray?

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.


1 Answers

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); } 
like image 154
Josh Avatar answered Oct 17 '22 23:10

Josh