How do i buffer an image from external link - c#

I have a external link with an image which i want to stream, but i get this error when i try.
error
"URI formats are not supported."
I tried to stream:
Stream fileStream = new FileStream("http://www.lokeshdhakar.com/projects/lightbox2/images/image-2.jpg", FileMode.Open);
byte[] fileContent = new byte[fileStream.Length];
can anyone put some light on this.
Thanks

The FileStream contructor you are using must be provided with a path on your local harddrive and not with an external URL.
You are probably looking for this:
string url = "http://www.lokeshdhakar.com/projects/lightbox2/images/image-2.jpg";
HttpWebRequest httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(url);
HttpWebResponse httpWebReponse = (HttpWebResponse)httpWebRequest.GetResponse();
Stream stream = httpWebReponse.GetResponseStream();
Probably also for this:
Image pic = Image.FromStream(stream);
MemoryStream ms = new MemoryStream();
pic.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
Byte[] arr = ms.ToArray();

FileStream doesn't support the opening files over the internet.
Try this:
var webClient = new WebClient();
using(var fileStream = webClient.OpenRead("http://www.lokeshdhakar.com/projects/lightbox2/images/image-2.jpg"))
{
byte[] fileContent = new byte[fileStream.Length];
}

Related

REST response trying to IMG or other filetype

Ive got a question I am having a case of rest response that is always string, it suppose to download content of the file, but there can be many different files, for example PNG, now if I'm getting a string in response is it possible to convert it back to PNG at the end, I tried something like:
byte[] array = Encoding.ASCII.GetBytes(result.data); //response content
MemoryStream ms = new MemoryStream(array);
Image i = Image.FromStream(ms);
I dont think im getting base64 string from rest looks like (part of it, and if i remmebr base64 ends with 3 === and don't have any non printable chars):
�PNG\r\n\n\0\0\0\rIHDR\0\0�\0\0\0�\b\0\0\0���\0\0\0sRGB\0���\0\0\0gAMA\0\0��\v�a\0\0\0\tpHYs\0\0t\0\0t�fx\0\0\f\aIDATx^��!x�L���Jde%�yY�D�H$�d%2��S��Hd%y�<�ӹ�B�ٝ�O�mﺔ��d����\r\0���\a�(H|\0���\a�(H|\0���\a�(H|\0���\a�(H|\0���\a�(H|\0���\a�(H|\0���\a�(H|\0���\a�(H|\0���\a�(H|\0���\a�(H|\0�\"D�WU��v������r��o#\f!��y�����K�\0�'D�O�SM�\f�����\0��Dǯ�z4�R��C�7\0��+�\0�\0Q��\0�\0Q��UU���ļO ?�������!�#J�>���|D��$>\f�|D��$>\f��7X,�?�_\v]�V�^/�=��#4$�����$:��P9
Assuming you are returning base 64 string from the API response, you can do something like this
byte[] bytes = Convert.FromBase64String(result.data);
Image image;
using (MemoryStream ms = new MemoryStream(bytes))
{
image = Image.FromStream(ms);
}
return image;
Or you can save it directly to the file
string filePath = "Image.png";
File.WriteAllBytes(filePath, Convert.FromBase64String(result.data));
EDIT 1:
How are you returning data from your web API? You could do something like this to return byte array and then use this array directly to write to stream.
var result = new HttpResponseMessage(HttpStatusCode.OK);
String filePath = HostingEnvironment.MapPath("~/imagename.png");
FileStream fileStream = new FileStream(filePath, FileMode.Open);
Image image = Image.FromStream(fileStream);
MemoryStream memoryStream = new MemoryStream();
image.Save(memoryStream, ImageFormat.Jpeg);
result.Content = new ByteArrayContent(memoryStream.ToArray());
result.Content.Headers.ContentType = new MediaTypeHeaderValue("image/png");
return result;
and on the client side you can do something like
var data = response.Content.ReadAsByteArrayAsync().Result;
Image image;
using (MemoryStream ms = new MemoryStream(data))
{
image = Image.FromStream(ms);
}
return image;

Zip file from URL not valid

I followed another post to be able to zip the content of an URL..
When I click my button Download, I "zip" the content of the URL and I save it in the default download folder...
So far this is my code:
WebClient wc = new WebClient();
ZipFile zipFile = new ZipFile();
string filename = "myfile.zip";
zipFile.Password = item.Password;
Stream s = wc.OpenRead(myUrl);
zipFile.AddeEntry(filename, s);
return File(s, "application/zip", filename);
it´s similar to this one (which zips the content of a folder... ) (It works correctly)
ZipFile zipFile = new ZipFile();
zipFile.Password = item.Password;
zipFile.AddDirectory(sourcePath, "");
MemoryStream stream = new MemoryStream();
zipFile.Save(stream);
zipFile.Dispose();
stream.Seek(0, SeekOrigin.Begin);
return File(stream, "application/zip", fileName);
So, I want to do exactly the same with an URL..
THanks!
at the end I use this code and It works like I wanted...
Thanks to all again!
string fileName = "filename" + ".zip";
MemoryStream stream = new MemoryStream();
ZipFile zipFile = new ZipFile();
WebRequest webRequest = WebRequest.Create(myUrl);
webRequest.Timeout = 1000;
WebResponse webResponse = webRequest.GetResponse();
using (StreamReader reader = new StreamReader(webResponse.GetResponseStream()))
{
string content = reader.ReadToEnd();
zipFile.AddEntry("myfile.txt", content);
}
zipFile.Save(stream);
zipFile.Dispose();
stream.Seek(0, SeekOrigin.Begin);
return File(stream, "application/zip", fileName);
The example you provide will create an entry inside your zip file with the contents from the stream but you are doing nothing to save and return the actual zip file. You need to use the creation code from your second example.
// name of zip file
string filename = "myfile.zip";
// filename of content
string contentName = "mypage.html";
WebClient wc = new WebClient();
ZipFile zipFile = new ZipFile();
zipFile.Password = item.Password;
Stream s = wc.OpenRead(myUrl);
zipFile.AddeEntry(contentName, s);
MemoryStream stream = new MemoryStream();
zipFile.Save(stream);
zipFile.Dispose(); // could use using instead
s.Dispose(); // could use using instead....
stream.Seek(0, SeekOrigin.Begin);
return File(stream, "application/zip", fileName);
this will return a zip file with one file in it called content.html containing the contents of the url stream

Trying to convert Byte[] to bitmap but giving error saying "parameter is not valid" in c#

public class PrintPage
{
public void buildPdf(string url)
{
Bitmap bmp = PrintHelpPage(url);
Document dc = new Document();
PdfWriter pdfWrt = PdfWriter.GetInstance(dc, new FileStream(#"D:/Experiment/Sample.pdf", FileMode.Create));
dc.Open();
iTextSharp.text.Image pdfImage = iTextSharp.text.Image.GetInstance(bmp, System.Drawing.Imaging.ImageFormat.Jpeg);
dc.Add(pdfImage);
dc.Close();
}
private Bitmap PrintHelpPage(string url)
{
if (url.ToUpper()=="DEFAULT")
{
url = #"https://www.google.com";
}
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
System.Text.Encoding Enc = System.Text.Encoding.GetEncoding(response.CharacterSet);
StreamReader sr = new StreamReader(response.GetResponseStream(), Enc);
string sDoc = sr.ReadToEnd();
sr.Close();
byte[] by = Encoding.ASCII.GetBytes(sDoc);
Bitmap bm = ByteToImage(by);
return bm;
}
public static Bitmap ByteToImage(byte[] blob)
{
using (MemoryStream mStream = new MemoryStream())
{
mStream.Write(blob, 0, blob.Length);
mStream.Seek(0, SeekOrigin.Begin);
Bitmap bm = new Bitmap(mStream);
return bm;
}
}
}
EDIT: Subsequent to your comment:
actually I am trying to capture whole page as a picture of a random website to convert as PDF
Then you're going about it the wrong way. You'll need to start a browser (e.g. a System.Windows.Forms.WebBrowser) and somehow do a screen capture. This will be non-trivial. It's also important that you understand why your current approach doesn't work - it suggests a fundamental misunderstanding of how the web works.
Original answer
This is your most fundamental problem:
System.Text.Encoding Enc = System.Text.Encoding.GetEncoding(response.CharacterSet);
StreamReader sr = new StreamReader(response.GetResponseStream(), Enc);
string sDoc = sr.ReadToEnd();
sr.Close();
byte[] by = Encoding.ASCII.GetBytes(sDoc);
You're reading an image as if it were a text file. It won't be. You'll be losing data like this.
Additionally, you're closing the memory stream that you're passing into the Bitmap constructor - you shouldn't do that.
You should just copy the response stream directly into a MemoryStream, and use that for the Bitmap:
MemoryStream stream = new MemoryStream();
using (var input = response.GetResponseStream())
{
input.CopyTo(stream);
}
stream.Position = 0;
Bitmap bitmap = new Bitmap(stream);
Oh, and you should also use a using statement for the response, otherwise that won't get disposed, which can cause timeouts for future requests due to connection pooling.

Get dynamically generated image into win form

I am trying to get an image via HttpWebRequest and show it in the win form imagebox. While tracking the request via Fiddler ImageView tab I can see that image can be seen correctly but while reading the stream I got Stream was not readable error on
Image img = Image.FromStream(stream).
What am I missing?
HttpWebRequest req = HttpWebRequest request = (HttpWebRequest)WebRequest.Create("[URL here]");
HttpWebResponse response = (HttpWebResponse)req.GetResponse();
Stream stream = response.GetResponseStream();
Image img = Image.FromStream(stream); // ERROR occurs here
stream.Close();
After some digging found an answer here C# gif Image to MemoryStream and back (lose animation):
HttpWebRequest req = HttpWebRequest request = (HttpWebRequest)WebRequest.Create("[URL here]");
HttpWebResponse response = (HttpWebResponse)req.GetResponse();
Stream stream = response.GetResponseStream();
MemoryStream memoryStream = new MemoryStream();
stream.CopyTo(memoryStream);
memoryStream.Position = 0;
stream = memoryStream;
Image img = Image.FromStream(stream);
stream.Close();

How to create Bitmap from file on server - parameter is not valid

HttpRequest req = new HttpRequest(imageName, "http://panonest.com", "");
var imgSrc=req.MapPath("~/view/vacantapredeal/vacantapredeal.jpg");
Bitmap img = new Bitmap(imgSrc);
How should I do this? I get a parameter is not valid exception, which is thrown by the Bitmap constructor.
here is another way to do it:
WebClient MyWebClient = new WebClient();
byte[] BytesImage = MyWebClient.DownloadData("http://www.google.com/intl/en_com/images/srpr/logo3w.png");
System.IO.MemoryStream iStream= new System.IO.MemoryStream(BytesImage);
System.Drawing.Bitmap b = new System.Drawing.Bitmap(iStream);
Good luck!
If you are just loading the image from your local server you can do it easily using System.Drawing.Image:
System.Drawing.Bitmap bmp =
new System.Drawing.Bitmap(System.Drawing.Image.FromFile(
MapPath("~/view/vacantapredeal/vacantapredeal.jpg")));
If this is an image on a remote server, then according to MSDN, you need to do something like:
System.Net.WebRequest request = System.Net.WebRequest.Create("http://panonest.com" + imageName);
System.Net.WebResponse response = request.GetResponse();
System.IO.Stream responseStream = response.GetResponseStream();
Bitmap bitmap2 = new Bitmap(responseStream);
bitmap2.Save("~/view/vacantapredeal/vacantapredeal.jpg");

Categories

Resources