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);
}
}
Related
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'm trying to return a file in a ASP.NET Web API Controller. This file is a dynamically-generated PDF saved in a MemoryStream.
The client (browser) receives the file successfully, but when I open the file, I see that all the pages are totally blank.
The thing is that if I take the same MemoryStream and write it to a file, this disk file is displayed correctly, so I assume that the problem is related to the file transfer via Web.
My controller looks like this:
[HttpGet][Route("export/pdf")]
public HttpResponseMessage ExportAsPdf()
{
MemoryStream memStream = new MemoryStream();
PdfExporter.Instance.Generate(memStream);
memStream.Position = 0;
HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
result.Content = new ByteArrayContent(memStream.ToArray()); //OR: new StreamContent(memStream);
return result;
}
Just to try, if I write the stream to disk, it's displayed correctly:
[HttpGet][Route("export/pdf")]
public HttpResponseMessage ExportAsPdf()
{
MemoryStream memStream = new MemoryStream();
PdfExporter.Instance.Generate(memStream);
memStream.Position = 0;
using (var fs = new FileStream("C:\\Temp\\test.pdf", FileMode.OpenOrCreate, FileAccess.ReadWrite))
{
memStream.CopyTo(fs);
}
return null;
}
The differences are:
PDF saved on disk: 34KB
PDF transferred via web: 60KB (!)
If I compare both files contents, the main differences are:
File Differences
On the left is the PDF transferred via web; on the right, the PDF saved to disk.
Is there something wrong with my code?
Maybe something related to encodings?
Thanks!
Well, it turned out to be a client (browser) problem, not a server problem. I'm using AngularJS in the frontend, so when the respose was received, Angular automatically converted it to a Javascript string. In that conversion, the binary contents of the file were somehow altered...
Basically it was solved by telling Angular not to convert the response to a string:
$http.get(url, { responseType: 'arraybuffer' })
.then(function(response) {
var dataBlob = new Blob([response.data], { type: 'application/pdf'});
FileSaver.saveAs(dataBlob, 'myFile.pdf');
});
And then saving the response as a file, helped by the Angular File Saver service.
I guess you should set ContentDisposition and ContentType like this:
[HttpGet][Route("export/pdf")]
public HttpResponseMessage ExportAsPdf()
{
MemoryStream memStream = new MemoryStream();
PdfExporter.Instance.Generate(memStream);
var result = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new ByteArrayContent(memStream.ToArray())
};
//this line
result.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
{
FileName = "YourName.pdf"
};
//and this line
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
return result;
}
Try this
[HttpGet][Route("export/pdf")]
public HttpResponseMessage ExportAsPdf()
{
MemoryStream memStream = new MemoryStream();
PdfExporter.Instance.Generate(memStream);
//get buffer
var buffer = memStream.GetBuffer();
//content length for header
var contentLength = buffer.Length;
var statuscode = HttpStatusCode.OK;
var response = Request.CreateResponse(statuscode);
response.Content = new StreamContent(new MemoryStream(buffer));
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
response.Content.Headers.ContentLength = contentLength;
ContentDispositionHeaderValue contentDisposition = null;
if (ContentDispositionHeaderValue.TryParse("inline; filename=my_filename.pdf", out contentDisposition)) {
response.Content.Headers.ContentDisposition = contentDisposition;
}
return response;
}
I have a list of Image's address. With this code I can read the Image correctly :
List<Image> ImageList = new List<Image>();
List<string> fileNameList = new List<string>();
foreach (var fileName in fileNameList)
{
var request = WebRequest.Create(fileName);
request.Method = WebRequestMethods.Ftp.DownloadFile;
request.Credentials = new NetworkCredential(Username, Password);
using (var response = (FtpWebResponse)request.GetResponse())
using (var stream = response.GetResponseStream())
using (var img = Image.FromStream(stream))
{
img.Save(#"D:\ax.jpg", ImageFormat.Jpeg);
ImageList.Add(img);
}
}
Until this line ImageList.Add(img); both of the img and the item in ImageList are true. But when it's coming out of the last using, all of the ImageList's properties changes to "threw an exception of type 'System.ArgumentException'"
For example for property of Height it changed to :
'((new System.Collections.Generic.Mscorlib_CollectionDebugView<System.Drawing.Image>(ImageList)).Items[0]).Height' threw an exception of type 'System.ArgumentException'
What's wrong with my code?
don't use using statement for image, it will dispose image when leave the block
using (var stream = response.GetResponseStream())
{
var img = Image.FromStream(stream);
img.Save(#"D:\ax.jpg", ImageFormat.Jpeg);
ImageList.Add(img);
}
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;
I have to retrieve an image from the disk or a web link , resize it and stream it to the client app. This is my controller method.
[HttpPost]
[ActionName("GetImage")]
public HttpResponseMessage RetrieveImage(ImageDetails details)
{
if (!details.Filename.StartsWith("http"))
{
if (!FileProvider.Exists(details.Filename))
{
throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound, "File not found"));
}
var filePath = FileProvider.GetFilePath(details.Filename);
details.Filename = filePath;
}
var image = ImageResizer.RetrieveResizedImage(details);
MemoryStream stream = new MemoryStream();
// Save image to stream.
image.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
var response = new HttpResponseMessage();
response.Content = new StreamContent(stream);
response.Content.Headers.ContentDisposition
= new ContentDispositionHeaderValue("attachment");
response.Content.Headers.ContentDisposition.FileName = details.Filename;
response.Content.Headers.ContentType
= new MediaTypeHeaderValue("application/octet-stream");
return response;
}
And this is how am sending the web link(in this case) and receiving the image at the client app end.
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:27066");
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/octet-stream"));
ImageDetails img = new ImageDetails { Filename = "http://2.bp.blogspot.com/-W6kMpFQ5pKU/TiUwJJc8iSI/AAAAAAAAAJ8/c3sJ7hL8SOw/s1600/2011-audi-q7-review-3.jpg", Height = 300, Width = 200 };
var response = await client.PostAsJsonAsync("api/Media/GetImage", img);
response.EnsureSuccessStatusCode(); // Throw on error code.
var stream = await response.Content.ReadAsStreamAsync();
FileStream fileStream = System.IO.File.Create("ImageName");
// Initialize the bytes array with the stream length and then fill it with data
byte[] bytesInStream = new byte[stream.Length];
stream.Read(bytesInStream, 0, (int)bytesInStream.Length);
// Use write method to write to the specified file
fileStream.Write(bytesInStream, 0, (int) bytesInStream.Length);
MessageBox.Show("Uploaded");
The image is being retrieved from the web link and the resizing is done properly but am not sure if its being streamed proeprly as its creating a 0kb file with "ImageName" when received at client app. Can anyone please tell me where am going wrong? I have been banging my head about it all day :(
Try resetting the position of the memory stream before passing it to the response:
stream.Position = 0;
response.Content = new StreamContent(stream);
I suppose that your image resizing library is leaving the position of the memory stream at the end.