I want to check size image from url in C#.
Ex: Url: http://img.khoahoc.tv/photos/image/2015/05/14/hang_13.jpg
Download and check:
string image = #"http://img.khoahoc.tv/photos/image/2015/05/14/hang_13.jpg";
byte[] imageData = new WebClient().DownloadData(image);
MemoryStream imgStream = new MemoryStream(imageData);
Image img = Image.FromStream(imgStream);
int wSize = img.Width;
int hSize = img.Height;
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(#"http://img.khoahoc.tv/photos/image/2015/05/14/hang_13.jpg";);
HttpWebResponse response = (HttpWebResponse)req.GetResponse();
Stream stream = response.GetResponseStream();
Image img = Image.FromStream(stream);
stream.Close();
MessageBox.Show("Height: " + img.Height + " Width: " + img.Width);
For optimization, I suggest to use #Backs answer with async/await to download the image:
public async Task<Size> GetImageSizeFromUrl(string url)
{
var imageData = await new System.Net.WebClient().DownloadDataTaskAsync(url);
var imgStream = new MemoryStream(imageData);
var img = System.Drawing.Image.FromStream(imgStream);
return new Size(img.Width, img.Height);
}
Related
This is my URL
http://nry.hr2eazy.com//Modules//UserManagement//ImageLoader.ashx?PortalSettingId=1
I am using this code but the image not shown in PictureBox.
System.Net.WebRequest request =
System.Net.WebRequest.Create("http://daikin.hr2eazy.com//Modules/UserManagement/ImageLoader.ashx?PortalSettingId=1");
System.Net.WebResponse response = request.GetResponse();
System.IO.Stream responseStream =
response.GetResponseStream();
Bitmap bitmap2 = new Bitmap(responseStream);
pictureBox11.Image = bitmap2;
You could use the Load(string) method like:
myPictureBox.Load("https://i.picsum.photos/id/237/200/300.jpg?hmac=TmmQSbShHz9CdQm0NkEjx1Dyh_Y984R9LpNrpvH2D_U");
Your url is returning as plain text, so there's a little more work to load it, but that should do it:
HttpClient client = new HttpClient();
var response = client.GetAsync("http://nry.hr2eazy.com//Modules//UserManagement//ImageLoader.ashx?PortalSettingId=1").Result;
var imageStream = response.Content.ReadAsStreamAsync().Result;
Bitmap img = new Bitmap(imageStream);
pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
pictureBox1.Image = img;
I tried to convert my image from camera to byte[] and then make request to my server but it is not working so my image from camera is
var image = textureView.Bitmap;
image = Android.Graphics.Bitmap.CreateBitmap
(image,
(int)OCR_Rectangle.GetX(),
(int)OCR_Rectangle.GetY(),
OCR_Rectangle.Width,
OCR_Rectangle.Height);
My web request is
public async static Task<string> ParseAsync(byte[] image)
{
string id = "my id ";
string apiKey = "my api key ";
using (var httpClient = new HttpClient())
{
httpClient.DefaultRequestHeaders.TryAddWithoutValidation("app_id", id);
httpClient.DefaultRequestHeaders.TryAddWithoutValidation("app_key", apiKey);
var base64 = Convert.ToBase64String(image);
var imageUri = "data:image/jpg;base64," + base64;
var json = JsonConvert.SerializeObject(new { src = imageUri });
var content = new StringContent(json, System.Text.Encoding.UTF8, "application/json");
var response = await httpClient.PostAsync("my website", content);
var dynObj = JsonConvert.DeserializeObject<RootObjectLatex>(await response.Content.ReadAsStringAsync());
return dynObj.latex;
}
}
Here is my attempt to convert bitmap to byte[]
byte[] bitmapData;
using (var stream = new MemoryStream())
{
image.Compress(Bitmap.CompressFormat.Png, 0, stream);
bitmapData = stream.ToArray();
}
And then i want to use bitmapData in my request.But no luck.
So, I found error this works
byte[] bitmapData;
using (var stream = new MemoryStream())
{
image.Compress(Bitmap.CompressFormat.Png, 0, stream);
bitmapData = stream.ToArray();
}
but i type wrong api key in my request
I am in the process of uploading images to Amazon S3, however i keep getting the error "Please specify either a Filename, provide a FileStream or provide a ContentBody to PUT an object into S3."
Basically i am uploading an image from a fileupload control and then hitting the code below. It uploads locally fine, but not to Amazon. The Credentials are alright so it only errors when it comes to uplaoding.
Can anyone see why this is happening please?
protected void uploadImg(int prodId, int prodFormat)
{
if (imgPack.HasFile)
{
string fileExt = Path.GetExtension(imgPack.PostedFile.FileName);
string filename = "img" + prodId + ".jpg";
// Specify the upload directory
string directory = Server.MapPath(#"\images\packshots\");
if (fileExt == ".jpeg" || fileExt == ".jpg" || fileExt == ".png")
{
if (packUK.PostedFile.ContentLength < 716800)
{
// Create a bitmap of the content of the fileUpload control in memory
Bitmap originalBMP = new Bitmap(packUK.FileContent);
// Calculate the new image dimensions
decimal origWidth = originalBMP.Width;
decimal origHeight = originalBMP.Height;
decimal sngRatio = origHeight / origWidth;
int newHeight = 354; //hight in pixels
decimal newWidth_temp = newHeight / sngRatio;
int newWidth = Convert.ToInt16(newWidth_temp);
// Create a new bitmap which will hold the previous resized bitmap
Bitmap newBMP = new Bitmap(originalBMP, newWidth, newHeight);
// Create a graphic based on the new bitmap
Graphics oGraphics = Graphics.FromImage(newBMP);
// Set the properties for the new graphic file
oGraphics.SmoothingMode = SmoothingMode.AntiAlias;
oGraphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
// Draw the new graphic based on the resized bitmap
oGraphics.DrawImage(originalBMP, 0, 0, newWidth, newHeight);
// Save the new graphic file to the server
string accessKey = "KEY HERE";
string secretKey = "KEY HERE";
AmazonS3 client;
using (client = Amazon.AWSClientFactory.CreateAmazonS3Client(accessKey, secretKey))
{
PutObjectRequest request = new PutObjectRequest();
request.BucketName="MyBucket";
request.CannedACL = S3CannedACL.PublicRead;
request.Key = "images/" + filename;
S3Response response = client.PutObject(request);
}
//newBMP.Save(directory + filename);
// Once finished with the bitmap objects, we deallocate them.
originalBMP.Dispose();
newBMP.Dispose();
oGraphics.Dispose();
}
}
else
{
notifybar.Attributes.Add("style", "display:block;");
notifybar.Attributes.Add("class", "failed");
notifyText.Text = "Error Text Here";
}
}
else
{
notifybar.Attributes.Add("style", "display:block;");
notifybar.Attributes.Add("class", "failed");
notifyText.Text = "Error Text Here";
}
}
You need to assign File or InputStream property of PutObjectRequest object. The code fragment should look like this one:
using (client = Amazon.AWSClientFactory.CreateAmazonS3Client(accessKey, secretKey))
{
var stream = new System.IO.MemoryStream();
originalBMP.Save(stream, ImageFormat.Bmp);
stream.Position = 0;
PutObjectRequest request = new PutObjectRequest();
request.InputStream = stream;
request.BucketName="MyBucket";
request.CannedACL = S3CannedACL.PublicRead;
request.Key = "images/" + filename;
S3Response response = client.PutObject(request);
}
I used the favicon-code I found here to retrieve the favicon of the site loaded in the browser element.
I want to use this favicon as the icon of my Windows Form.
Thanks to JP Hellemons this code works:
private void browser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) {
this.Icon = favicon(GetActiveBrowser().Url);
}
private WebBrowser GetActiveBrowser() {
return (WebBrowser)tabs.SelectedTab.Controls[0];
}
private Icon favicon(Uri url) {
WebRequest request = (HttpWebRequest)WebRequest.Create("http://" + url.Host + "/favicon.ico");
Bitmap bm = new Bitmap(32, 32);
MemoryStream memStream;
using (Stream response = request.GetResponse().GetResponseStream()) {
memStream = new MemoryStream();
byte[] buffer = new byte[1024];
int byteCount;
do {
byteCount = response.Read(buffer, 0, buffer.Length);
memStream.Write(buffer, 0, byteCount);
} while (byteCount > 0);
}
bm = new Bitmap(Image.FromStream(memStream));
if (bm != null) {
Icon ic = Icon.FromHandle(bm.GetHicon());
return ic;
} else
return Properties.Resources.GZbrowser;
}
According to this documentation, it should work from stream.
http://msdn.microsoft.com/en-us/library/system.drawing.icon.aspx
I used this article: http://odetocode.com/Blogs/scott/archive/2004/10/05/webrequest-and-binary-data.aspx
WebRequest request = (HttpWebRequest)WebRequest.Create("http://" + url.Host + "/favicon.ico");
Icon ic = new Icon(); // put default here
Bitmap bm = new Bitmap();
try
{
using(WebResponse response = request.GetResponse())
{
using(Stream responseStream = response.GetResponseStream())
{
using(MemoryStream ms = new MemoryStream())
{
var tmp = Image.FromStream(ms); // changed bitmap to image
bm = new Bitmap(tmp);
}
}
}
}catch{}
if(bm != null)
{
ic = Icon.FromHandle(bm.GetHicon);
}
return ic;
Edit: something like this should do it
Edit2: changed some things in the answer. Can you try this?
Final edit: (lol)
Just tested this in a windows form app and this works! :)
Uri url = new Uri("http://www.google.nl");
WebRequest request = (HttpWebRequest)WebRequest.Create("http://" + url.Host + "/favicon.ico");
Bitmap bm = new Bitmap(32,32);
MemoryStream memStream;
using (Stream response = request.GetResponse().GetResponseStream())
{
memStream = new MemoryStream();
byte[] buffer = new byte[1024];
int byteCount;
do
{
byteCount = response.Read(buffer, 0, buffer.Length);
memStream.Write(buffer, 0, byteCount);
} while (byteCount > 0);
}
bm = new Bitmap(Image.FromStream(memStream));
if (bm != null)
{
Icon ic = Icon.FromHandle(bm.GetHicon());
this.Icon = ic;
}
Read response byte array first, than create MemoryStream of it and create icon from that MemoryStream.
Network stream do not support seek operations that seem to be necessary for creating an icon.
I am using the below code. I just dont know why it is not working. The error msg is : Unspecified error on this : bmp.SetSource(ms).
I am not familiar with HttpWebRequest for Wp7. Would appreciate your help to solve this problem. Thanks.
enter code here
private void LoadPic()
{
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(#"http://xxxxxx/MyImage.jpg");
NetworkCredential creds = new NetworkCredential("Username", "Pwd");
req.Credentials = creds;
req.Method = "GET";
req.BeginGetResponse(new AsyncCallback(GetStatusesCallBack), req);
}
public void GetStatusesCallBack(IAsyncResult result)
{
try
{
HttpWebRequest httpReq = (HttpWebRequest)result.AsyncState;
HttpWebResponse response = (HttpWebResponse)httpReq.EndGetResponse(result);
Stream myStream = response.GetResponseStream();
int len = (int)myStream.Length;
byte[] byt = new Byte[len];
myStream.Read(byt, 0, len);
myStream.Close();
MemoryStream ms = new MemoryStream(byt);
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
BitmapImage bmp = new BitmapImage();
bmp.SetSource(ms);
image1.Source = bmp;
});
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Is it necessary to copy the response stream to a byte array and then to a MemoryStream? If not, you can just do the following:
Stream myStream = response.GetResponseStream();
Deployment.Current.Dispatcher.BeginInvoke(() => {
BitmapImage bmp = new BitmapImage();
bmp.SetSource(myStream);
image1.Source = bmp;
});
If you have to do the copy for some reason, you will need to fill the buffer in a loop:
Stream myStream = response.GetResponseStream();
int contentLength = (int)myStream.Length;
byte[] byt = new Byte[contentLength];
for (int pos = 0; pos < contentLength; )
{
int len = myStream.Read(byt, pos, contentLength - pos);
if (len == 0)
{
throw new Exception("Upload aborted.");
}
pos += len;
}
MemoryStream ms = new MemoryStream(byt);
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
// same as above
});
Second part adapted (slightly) from C# bitmap images, byte arrays and streams!.