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

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");

Related

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 download an image from an URI and create a bitmap object from it?

I'm trying to download image from a website and create bitmap based on that image. It looks like this:
public void test()
{
PostWebClient client = new PostWebClient(callback);
cookieContainer = new CookieContainer();
client.cookies = cookieContainer;
client.download(new Uri("SITE"));
}
public void callback(bool error, string res)
{
byte[] byteArray = UnicodeEncoding.UTF8.GetBytes(res);
MemoryStream stream = new MemoryStream( byteArray );
var tmp = new BitmapImage();
tmp.SetSource(stream);
}
I receive "Unspecified error" on last line of callback method. Interesting fact is that if I use BitmapImage(new Uri("SITE")) it works well... (I can't do this like that because I want to grab cookies from that URL. The image is an jpg.
PostWebClient class -> http://paste.org/53413
This is the simplest code from Bitmap class documentation.
System.Net.WebRequest request =
System.Net.WebRequest.Create(
"http://www.microsoft.com//h/en-us/r/ms_masthead_ltr.gif");
System.Net.WebResponse response = request.GetResponse();
System.IO.Stream responseStream =
response.GetResponseStream();
Bitmap bitmap2 = new Bitmap(responseStream);
MSDN link for Bitmap
The easiest way is to open a network stream via a WebClient instance and pass it to the constructor of the Bitmap class:
using (WebClient wc = new WebClient())
{
using (Stream s = wc.OpenRead("http://hell.com/leaders/cthulhu.jpg"))
{
using (Bitmap bmp = new Bitmap(s))
{
bmp.Save("C:\\temp\\octopus.jpg");
}
}
}
You can try below code:
private Bitmap LoadPicture(string url)
{
HttpWebRequest wreq;
HttpWebResponse wresp;
Stream mystream;
Bitmap bmp;
bmp = null;
mystream = null;
wresp = null;
try
{
wreq = (HttpWebRequest)WebRequest.Create(url);
wreq.AllowWriteStreamBuffering = true;
wresp = (HttpWebResponse)wreq.GetResponse();
if ((mystream = wresp.GetResponseStream()) != null)
bmp = new Bitmap(mystream);
}
finally
{
if (mystream != null)
mystream.Close();
if (wresp != null)
wresp.Close();
}
return (bmp);
}
try this:
string url ="http://www.google.ru/images/srpr/logo11w.png"
PictureBox picbox = new PictureBox();
picbox.Load(url);
Bitmap bitmapRemote = (Bitmap) picbox.Image;
url - internet image , we create new instance object PictureBox, then calling NOT ASYNC procedure to load image from url, when image retrieved get image as bitmap.
Also you can use Threading to work with form, call load in other thread and pass deleate method to retrieve image when complete .

Windows Phone 7- Set an Image source to a stream in memory

Is it possible to set the source of an image in WP7 to a stream? Normally I'd use BitmapImage to do this in Silverlight but I don't see that option in WP7. Here's my code:
var request = WebRequest.CreateHttp("http://10.1.1.1/image.jpg");
request.Credentials = new NetworkCredential("user", "password");
request.BeginGetResponse(result =>
{
var response = request.EndGetResponse(result);
var stream = response.GetResponseStream();
// myImage.Source = ??
}, null);
The reason I ask is because I need to provide credentials to get the image - if there's another way to approach the problem I'm open to suggestions.
Yes, use this code:
var bi = new BitmapImage();
bi.SetSource(stream);
myImage.Source = bi;
In case WritableBitmap you can use:
WriteableBitmap wbmp = new WriteableBitmap(1000, 1000);
Extensions.LoadJpeg(wbmp, stream);
Image img = new Image();
img.Source = wbmp;
Try this one
<Image Name="Img" Stretch="UniformToFill" />
var bitImg= new BitmapImage();
bitImg.SetSource(stream); // stream is Stream type
Img.Source = bitImg;

How do i buffer an image from external link

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];
}

Categories

Resources