cannot download an image from server with authentication using c# in wpf - c#

am using following code to download image from server but failed.
am using server authentication please help
private BitmapImage getimage (string uri)
{
var webRequest = WebRequest.Create(uri);//making a variable webrequest,
webRequest.Credentials = new NetworkCredential("user", "password");//credential is using for authentication
using (var webResponse = webRequest.GetResponse())//use for stucking problem of button
{
using (var responseStream = webResponse.GetResponseStream())
{
BitmapImage img = new BitmapImage();
img.BeginInit();
img.StreamSource = responseStream;
img.EndInit();
return img;
}
}
}

The problem is that you are closing the response stream before the image is completely downloaded. In order to ensure that it is completely downloaded, you can copy it to an intermediate MemoryStream. Moreover, you will have to set the BitmapCacheOption.OnLoad flag if you want to close the stream immediately after EndInit. See the Remarks section in BitmapImage.StreamSource .
using (var webResponse = webRequest.GetResponse())
using (var responseStream = webResponse.GetResponseStream())
using (var memoryStream = new MemoryStream())
{
responseStream.CopyTo(memoryStream);
BitmapImage img = new BitmapImage();
img.BeginInit();
img.CacheOption = BitmapCacheOption.OnLoad;
img.StreamSource = memoryStream;
img.EndInit();
return img;
}
Alternatively you could delay the closing of the WebResponse until the image has been download completely. BitmapImage provides the DownloadCompleted and DownloadFailed event handlers for purposes like that. Note that closing the WebResponse also closes the response stream.
var webResponse = webRequest.GetResponse();
var img = new BitmapImage();
img.DownloadCompleted += (o, e) => webResponse.Close();
img.DownloadFailed += (o, e) => webResponse.Close();
img.BeginInit();
img.StreamSource = webResponse.GetResponseStream();
img.EndInit();
return img;

Related

How to convert a decode URL to bitmap and then shown the image in picturebox in winforms using c#.net

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;

Create image from stream with correct pixel format

I created a web service in .Net Core. This service return an image png with pixel format 8pp indexed :
using (Bitmap bmp = new Bitmap(img.width, img.height, PixelFormat.Format8bppIndexed))
{
using (MemoryStream ms = new MemoryStream())
{
bmp.Save(ms, imgFormat);
return new FileContentResult(ms.ToArray(), $"image/png");
}
}
I want to test this service, so I created a C# test with this piece of code :
Task<HttpResponseMessage> responseTask = client.PostAsync(url, content);
responseTask.Wait();
var response = responseTask.Result;
HttpContent ct = response.Content;
byte[] data = await ct.ReadAsByteArrayAsync();
using (MemoryStream m = new MemoryStream(data))
{
Bitmap img = new Bitmap(m);
img.Save(filePath, ImageFormat.Png);
}
But the Bitmap img is Format32bppArgb. How can I do to get my image in original format (Format8bppIndexed) ?
Just save straighway what you got:
using (var fs = new FileStream(filePath, FileMode.Create))
fs.Write(data, 0, data.Length);

C# Get icon from url as System.Drawing.Icon

I'm trying to put icons on a tab. I'm getting the icon from
http://google.com/favicon.ico for now.
I want to get the favicon.ico as System.Drawing.Icon. The original code I'm using is for a normal image, but I need it to be System.Drawing.Icon.
Here's my code so far:
var iconURL = "http://" + url.Host + "/favicon.ico";
System.Drawing.Icon img = null;
WebRequest request = WebRequest.Create(iconURL);
WebResponse response = request.GetResponse();
using (Stream stream = response.GetResponseStream())
{
img = new System.Drawing.Icon(stream);
// then use the image
}
qTabControl1.ActiveTabPage.Icon = img;
This gives me the following error:
You need to copy it to a stream that supports seeking, here is some sample code (using the newer HttpClient and async/await):
async Task<Icon> GetIcon()
{
var httpClient = new HttpClient();
using (var stream = await httpClient.GetStreamAsync(url))
using (var ms = new MemoryStream())
{
stream.CopyTo(ms);
ms.Seek(0, SeekOrigin.Begin); // See https://stackoverflow.com/a/72205381/640195
return new Icon(ms);
}
}

How to save images from web in Isolated Storage?

In my application I have list of urls to images. And what I need to do is download this images and save them in Isolated Storage.
What I already have:
using (IsolatedStorageFile localFile = IsolatedStorageFile.GetUserStoreForApplication()) {
...
foreach (var item in MyList)
{
Uri uri = new Uri(item.url, UriKind.Absolute);
BitmapImage bitmap = new BitmapImage(uri);
WriteableBitmap wb = new WriteableBitmap(bitmap);
using (IsolatedStorageFileStream fs = localFile.CreateFile(GetFileName(item.url)))//escape file name
{
wb.SaveJpeg(fs, wb.PixelWidth, wb.PixelHeight, 0, 85);
}
}
...
}
This code have place inside function in my App.xaml.cs file. I have tried many solutions, in this one the problem is "Invalid cross-thread access".
How can I make it work?
You get invalid cross-thread access if you create WriteableBitmap on non-UI thread. Ensure that that code is run on the main thread by using Dispatcher:
Deployment.Current.Dispatcher.BeginInvoke(() =>
// ...
);
Solution for this problem is:
foreach (var item in MyList)
{
Uri uri = new Uri(item.url, UriKind.Absolute);
HttpWebRequest request = HttpWebRequest.Create(uri) as HttpWebRequest;
request.BeginGetResponse((ar) =>
{
var response = request.EndGetResponse(ar);
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
using (var stream = response.GetResponseStream())
{
var name = GetFileName(item.url);
if (localFile.FileExists(name))
{
localFile.DeleteFile(name);
}
using (IsolatedStorageFileStream fs = localFile.CreateFile(name))
{
stream.CopyTo(fs);
}
}
});
}, null);
}
#Mateusz Rogulski
You should use WebClient, and i suggest you following solution for your problem. just try.
public string YourMethod(string yoursUri)
{
BitmapImage image=new BitmapImage();
WebClient client = new WebClient();
client.OpenReadCompleted += async (o, args) =>
{
Stream stream = new MemoryStream();
await args.Result.CopyToAsync(stream);
image.SetSource(stream);
};
client.OpenReadAsync(new Uri(yoursUri));//if passing object than you can write myObj.yoursUri
return image;
}
now you have image and you can save into your isolatedStorage with valid checks wherever you call this function

Displaying image from base64string

I'm displaying an image from a base 64 string that came from an API. The problem is, the image is not being displayed.
Here's the code:
profilePictureImg.Source = GetUserImage(user.MobileNumber);
private BitmapImage GetUserImage(string phoneNumber)
{
BitmapImage bitmapImage = new BitmapImage();
var baseAddress = "http://192.168.0.103/vchatapi/api/Images/" + phoneNumber;
var http = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(new System.Uri(baseAddress));
http.Accept = "application/json";
http.ContentType = "application/json";
http.Method = "GET";
var response = http.GetResponse();
var stream = response.GetResponseStream();
var sr = new StreamReader(stream);
var content = sr.ReadToEnd();
var y ="";
var x = y.FromJson(content);
byte[] binaryData = Convert.FromBase64String(x);
using (MemoryStream ms = new MemoryStream(binaryData, 0, binaryData.Length))
{
ms.Write(binaryData, 0, binaryData.Length);
bitmapImage.StreamSource = ms;
}
return bitmapImage;
}
Any Ideas?? Thanks!
EDIT:
Got the fix. For some reason, it requires to call BeginInit and EndInit.
The image may be decoded as shown in this answer:
var binaryData = Convert.FromBase64String(x);
var bitmapImage = new BitmapImage();
using (var stream = new MemoryStream(binaryData))
{
bitmapImage.BeginInit();
bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
bitmapImage.StreamSource = stream;
bitmapImage.EndInit();
}
The reason why you have to use BeginInit and EndInit is explained in the Remarks section of the BitmapImage MSDN documentation:
BitmapImage implements the ISupportInitialize interface to optimize
initialization on multiple properties. Property changes can only occur
during object initialization. Call BeginInit to signal that
initialization has begun and EndInit to signal that initialization has
completed. After initialization, property changes are ignored.
This may be one of those cases where it pays not to dispose the stream too eagerly; also, the Write here is unnecessary: you already added the data via the constructor. So just:
bitmapImage.StreamSource = new MemoryStream(binaryData);
return bitmapImage;
does that work?
You can try the following
byte[] binaryData = Convert.FromBase64String(x);
using (MemoryStream ms = new MemoryStream(binaryData))
{
bitmapImage = (Bitmap)Image.FromStream(ms);
}

Categories