0

I have the below program that converts an image to byte array

public byte[] ReadImageFile(string imageLocation)
        {
            byte[] imageData = null;
            FileInfo fileInfo = new FileInfo(imageLocation);
            long imageFileLength = fileInfo.Length;
            FileStream fs = new FileStream(imageLocation, FileMode.Open, FileAccess.Read);
            BinaryReader br = new BinaryReader(fs);
            imageData = br.ReadBytes((int)imageFileLength);
            return imageData;
        }

If I pass the value as "D:\\ENSource\\1.png", it works properly.

But If I send the value as "https://i.stack.imgur.com/PShuQ.png" it throws exception

URI formats are not supported

How can I achieve this?

Kevin Andrid
  • 1,963
  • 1
  • 15
  • 26
priyanka.sarkar
  • 25,766
  • 43
  • 127
  • 173
  • 1
    Use e.g. the `WebClient` class to download the image from an URI location. – Uwe Keim May 26 '15 at 03:44
  • You can't. **URI formats are not supported.** If you want to load an image over the internet, have a look [here](http://stackoverflow.com/questions/16091997/best-way-image-url-to-drawing-image?lq=1) – Blorgbeard May 26 '15 at 03:45

2 Answers2

5

FileInfo and FileStream work with local files, there is no way to "pass Uri" to either of them.

To handle Uri you can either:

  • map server to local drive (i.e. if server supports WebDAV).
  • use Http related classes (like HttpClient, WebClient) to download file from server and get bytes. I.e. Image to byte array from a url.
Community
  • 1
  • 1
Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
  • thanks Alexei... var webClient = new WebClient(); byte[] imageBytes = webClient.DownloadData("http://i.stack.imgur.com/PShuQ.png"); – priyanka.sarkar May 26 '15 at 03:48
1

Edit! Please see @Alexei's response. He tossed in a much better (read: simpler) solution that uses webclient. I'm leaving the response here in case someone wants to see a more "verbose" example of querying a web server.

I just gave Alexei an up tick (he's quite right), but just to fill this in . . .

Your communicating with a web server, not a file system. As a result, you will need to "request" the data from the server manually, and then pass the resulting stream.

Please see the following code snippet . . . http://www.digitalcoding.com/Code-Snippets/C-Sharp/C-Code-Snippet-Download-Image-from-URL.html

JFish222
  • 1,026
  • 7
  • 11