How to Use Httpwebrequest to Pull Image from Website to Local File

How to use httpwebrequest to pull image from website to local file

nice image :D

try using the following code:

you needed to use a BinaryReader, 'cause an image file is binary data and thus not encoded in UTF or ASCII

edit: using'ified

HttpWebRequest lxRequest = (HttpWebRequest)WebRequest.Create(
"http://www.productimageswebsite.com/images/stock_jpgs/34891.jpg");

// returned values are returned as a stream, then read into a string
String lsResponse = string.Empty;
using (HttpWebResponse lxResponse = (HttpWebResponse)lxRequest.GetResponse()){
using (BinaryReader reader = new BinaryReader(lxResponse.GetResponseStream())) {
Byte[] lnByte = reader.ReadBytes(1 * 1024 * 1024 * 10);
using (FileStream lxFS = new FileStream("34891.jpg", FileMode.Create)) {
lxFS.Write(lnByte, 0, lnByte.Length);
}
}
}
MessageBox.Show("done");

Using httpwebrequest to get image from website to byte[]

Got it working, want to post it here in case anyone needs it.

I need to get this image and then modify it (byte level) Silverlight didn't let me save the image directly to a WriteableBitmap and thus I had to get the image with a WebClient as a stream and then save it to a byte[]

this is how I get the image (I already have the specific Uri):

 WebClient wc = new WebClient();
wc.OpenReadCompleted += new OpenReadCompletedEventHandler(wc_OpenReadCompleted);
wc.OpenReadAsync(uri)

so when the image is loaded the wc_OpenReadCompleted method is called and it does something like this:

int lengthInBytes = Convert.ToInt32(e.Result.Length);
BinaryReader br = new BinaryReader(e.Result);

byte[] buffer = new byte[lengthInBytes];
using (br)
{
for (int i = 0; i < lengthInBytes; i++)
{
buffer[i] = br.ReadByte();
}
}

at the end the buffer[] has all the bytes of the image (what I wanted)
I'm sure there are better ways of doing this but this is working for me ! )

note: at some point I need to convert the byte[] to a BitmapImage (that was easier than expected):

        //imageInBytes is a byte[]

if (imageInBytes != null)
{
MemoryStream rawBytesStream = new MemoryStream(imageInBytes);
BitmapImage img = new BitmapImage();
img.SetSource(rawBytesStream);
return img;
}

I hope this helps anyone.

How do I programmatically save an image from a URL?

It would be easier to write something like this:

WebClient webClient = new WebClient();
webClient.DownloadFile(remoteFileUrl, localFileName);

How to download image from URL

Simply
You can use following methods.

using (WebClient client = new WebClient()) 
{
client.DownloadFile(new Uri(url), @"c:\temp\image35.png");
// OR
client.DownloadFileAsync(new Uri(url), @"c:\temp\image35.png");
}

These methods are almost same as DownloadString(..) and DownloadStringAsync(...). They store the file in Directory rather than in C# string and no need of Format extension in URi

If You don't know the Format(.png, .jpeg etc) of Image

public void SaveImage(string imageUrl, string filename, ImageFormat format)
{
WebClient client = new WebClient();
Stream stream = client.OpenRead(imageUrl);
Bitmap bitmap; bitmap = new Bitmap(stream);

if (bitmap != null)
{
bitmap.Save(filename, format);
}

stream.Flush();
stream.Close();
client.Dispose();
}

Using it

try
{
SaveImage("--- Any Image URL---", "--- Any Image Path ---", ImageFormat.Png)
}
catch(ExternalException)
{
// Something is wrong with Format -- Maybe required Format is not
// applicable here
}
catch(ArgumentNullException)
{
// Something wrong with Stream
}

Upload files with HTTPWebrequest (multipart/form-data)

I was looking for something like this, Found in :
http://bytes.com/groups/net-c/268661-how-upload-file-via-c-code (modified for correctness):

public static string UploadFilesToRemoteUrl(string url, string[] files, NameValueCollection formFields = null)
{
string boundary = "----------------------------" + DateTime.Now.Ticks.ToString("x");

HttpWebRequest request = (HttpWebRequest) WebRequest.Create(url);
request.ContentType = "multipart/form-data; boundary=" +
boundary;
request.Method = "POST";
request.KeepAlive = true;

Stream memStream = new System.IO.MemoryStream();

var boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" +
boundary + "\r\n");
var endBoundaryBytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" +
boundary + "--");

string formdataTemplate = "\r\n--" + boundary +
"\r\nContent-Disposition: form-data; name=\"{0}\";\r\n\r\n{1}";

if (formFields != null)
{
foreach (string key in formFields.Keys)
{
string formitem = string.Format(formdataTemplate, key, formFields[key]);
byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
memStream.Write(formitembytes, 0, formitembytes.Length);
}
}

string headerTemplate =
"Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n" +
"Content-Type: application/octet-stream\r\n\r\n";

for (int i = 0; i < files.Length; i++)
{
memStream.Write(boundarybytes, 0, boundarybytes.Length);
var header = string.Format(headerTemplate, "uplTheFile", files[i]);
var headerbytes = System.Text.Encoding.UTF8.GetBytes(header);

memStream.Write(headerbytes, 0, headerbytes.Length);

using (var fileStream = new FileStream(files[i], FileMode.Open, FileAccess.Read))
{
var buffer = new byte[1024];
var bytesRead = 0;
while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
{
memStream.Write(buffer, 0, bytesRead);
}
}
}

memStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);
request.ContentLength = memStream.Length;

using (Stream requestStream = request.GetRequestStream())
{
memStream.Position = 0;
byte[] tempBuffer = new byte[memStream.Length];
memStream.Read(tempBuffer, 0, tempBuffer.Length);
memStream.Close();
requestStream.Write(tempBuffer, 0, tempBuffer.Length);
}

using (var response = request.GetResponse())
{
Stream stream2 = response.GetResponseStream();
StreamReader reader2 = new StreamReader(stream2);
return reader2.ReadToEnd();
}
}

Download an image to local storage in Metro style apps

Looks like the code below from the HttpClient sample for Windows 8 solves the issue

    HttpRequestMessage request = new HttpRequestMessage(
HttpMethod.Get, resourceAddress);
HttpResponseMessage response = await rootPage.httpClient.SendAsync(request,
HttpCompletionOption.ResponseHeadersRead);

httpClient is a HttpClient, and its BaseAddress needs to be set a the server folder of your resource. we can then do this to convert that to an image source (if that's what we're downloading)

    InMemoryRandomAccessStream randomAccessStream = 
new InMemoryRandomAccessStream();
DataWriter writer = new DataWriter(randomAccessStream.GetOutputStreamAt(0));
writer.WriteBytes(await response.Content.ReadAsByteArrayAsync());
await writer.StoreAsync();
BitmapImage image = new BitmapImage();
imagecontrol.SetSource(randomAccessStream);

or this to write it to file

    var imageFile = await ApplicationData.Current.LocalFolder.CreateFileAsync(
filename, CreationCollisionOption.ReplaceExisting);
var fs = await imageFile.OpenAsync(FileAccessMode.ReadWrite);
DataWriter writer = new DataWriter(fs.GetOutputStreamAt(0));
writer.WriteBytes(await response.Content.ReadAsByteArrayAsync());
await writer.StoreAsync();
writer.DetachStream();
await fs.FlushAsync();


Related Topics



Leave a reply



Submit