RestSharp upload image with imagesource. (Image exist only as Variable) - c#

How to upload a Image with RestSharp without using a local path.
Image exists only in a Image Variable.
All i found was with a string as path, but this is not the way i want to go.
Or is it possible to get the string Path from a ImageSource?
How can this be solved?
My current code:
var client = new RestClient();
var request = new RestRequest(PostImageUrl, Method.Post);
request.AddOrUpdateHeader("Content-Type", "multipart/form-data");
request.AddFile("image", bauzeichnung);
request.AlwaysMultipartFormData = true;
var response = client.Execute(request);

It is not possible, every file is need a source. But I can suggest methods that I do not recommend.
You can convert image to base64 string and save image as string
You can take Url of image and show in your app. But in this case image is should be updated to network before(Url).
You can ConvertImage to base64 and store it in your cache.
You can convert Image to ByteArray.
None of these recommendations are correct methods!!!
The most accurate method;
You can take the image and store it in your machine(Local or Server). Then tahe the path of image and save database as Url(If you don't know the difference between url and path, you should research it). When you send image just send the url of your image.

Related

C#.Net Download Image from URL, Crop, and Upload without Saving or Displaying

I have a large number of images on a Web server that need to be cropped. I would like to automate this process.
So my thought is to create a routine that, given the URL of the image, downloads the image, crops it, then uploads it back to the server (as a different file). I don't want to save the image locally, and I don't want to display the image to the screen.
I already have a project in C#.Net that I'd like to do this in, but I could do .Net Core if I have to.
I have looked around, but all the information I could find for downloading an image involves saving the file locally, and all the information I could find about cropping involves displaying the image to the screen.
Is there a way to do what I need?
It's perfectly possible to issue a GET request to a URL and have the response returned to you as a byte[] using HttpClient.GetByteArrayAsync. With that binary content, you can read it into an Image using Image.FromStream.
Once you have that Image object, you can use the answer from here to do your cropping.
//Note: You only want a single HttpClient in your application
//and re-use it where possible to avoid socket exhaustion issues
using (var httpClient = new HttpClient())
{
//Issue the GET request to a URL and read the response into a
//stream that can be used to load the image
var imageContent = await httpClient.GetByteArrayAsync("<your image url>");
using (var imageBuffer = new MemoryStream(imageContent))
{
var image = Image.FromStream(imageBuffer);
//Do something with image
}
}

How to get image (mediaFile) from image storage path (File.path)

I have multiple local storage image path which is stored in sqlite and I have to upload these image on one click.
I have a string image path but I am not sure about how to use this.
I have store image path userinfo.FileName_LHSPic to list and now I want to get image and upload to server.
FileNameUpload userinfo = new FileNameUpload();
var file = await CrossMedia.Current.PickPhotoAsync(new Plugin.Media.Abstractions.PickMediaOptions
{
CompressionQuality = 50,
PhotoSize = Plugin.Media.Abstractions.PhotoSize.Medium
});
userinfo.FileName_LHSPic = file.Path;
One option is to use 'file' and turn it into a byte array, and store that in your database.
When it's time to upload, stream the byte array to the server (as part of a wider scoped class), and decode the file at the server end.

BitmapFrame - No imaging component suitable to complete this operation was found [duplicate]

I'm downloading in image from web to save it locally. It works great with any other image formats but it this method below fails with an argument exception when I try to read a WebP image.
private static Image GetImage(string url)
{
try
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
return Image.FromStream(response.GetResponseStream());
}
catch
{
return null;
}
}
How do you read .webp images in C#?
I found this other question that allows for converting between types but I do not want to do that WebP library for C#
Reason I'm not wanting to do it is because I think it might lose some quality. Besides, I want to know why is this not working.
The base class libraries won't help you to deal with WebP images. However, if you only want to save the received file to the disk, you don't have to even know that you are dealing with a WebP images. You can simply treat the received data as a binary blob and dump it to a file, for example using Stream.CopyTo and a FileStream.
The Content-Type HTTP header will give you the mime type of the file you're downloading, and the Content-Disposition header can provide you with a filename and extension (though you might have to do some parsing). You can access those using HttpWebResponse.ContentType and HttpWebResponse.Headers["Content-Disposition"].
#Trillian nailed it. Here is a code snippet for what I did based on his suggestion. Wanted to add code so not posting this as a comment.
To get just the image file extension, you can do this
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
string fileExt = response.ContentType.Replace("image/", string.Empty);
To get the file name with extension, you can do the following and the do parsing like I did above. It just has some more data in it.
response.Headers["Content-Disposition"];
Once you have you file name you want to save as, create a file stream and copy the response stream into it.
FileStream fs = new FileStream(targetPath + fileName, FileMode.Create);
response.GetResponseStream().CopyTo(fs);
Assuming you app has access to the destination, image should get saved. Make sure to add try catch and handle exceptions properly. Also note that FileMode.Create will overwrite if the file already exists!

How to display the skype user photo from HTTP Response using UCWA API?

I am working on Universal Windows Applications, in my current project I used Unified Communications Web API (UCWA) to display the skype user status it's working fine but when I am trying to display the skype user photo at that time I got stuck.
I followed below link to display the photo
https://msdn.microsoft.com/en-us/skype/ucwa/getmyphoto
I got response code of 200 OK for my GET request but I don't know how to display the image from my response.
Please tell me how to resolve it.
-Pradeep
I got Result, After getting HTTP Response then I am converting those response content to stream type by using this below line.
var presenceJsonStr = await httpResponseMessage.Content.ReadAsStreamAsync();
This is the code to display the image
var photo = await AuthenticationHelper.Photo();
// Create a .NET memory stream.
var memStream = new MemoryStream();
// Convert the stream to the memory stream, because a memory stream supports seeking.
await photo.CopyToAsync(memStream);
// Set the start position.
memStream.Position = 0;
// Create a new bitmap image.
var bitmap = new BitmapImage();
// Set the bitmap source to the stream, which is converted to a IRandomAccessStream.
bitmap.SetSource(memStream.AsRandomAccessStream());
// Set the image control source to the bitmap.
imagePreivew.ImageSource = bitmap;
Assuming you put an Accept header specifying an image type, you should be able to look at the Content-Length header to determine if the user has an image set on the server. If the length is zero you should consider providing a default image to be displayed. If not, I would suggest taking a look at Convert a Bitmapimage into a Byte Array and Vice Versa in UWP Platform as you should treat the response body as a byte array with its length defined by the Content-Length header.
If for some reason no Accept header was provided, the response body is not an image/* type, and looks like a string then you might be dealing with a Base64 encoded image. This case should be much less likely to deal with, but if you need advice I would suggest looking at Reading and Writing Base64 in the Windows Runtime.
You can directly use the URL generated for the user photo resource. Just set the URL of the image as the source of the Image container. You application would load it automatically.

Download images from web and use downloaded images when presen

My C# program needs to display, of many possible images, one at a time. The images are on the web and I have a precise URL for each one. The program needs to either load the image from the web or, if it has been loaded previously, load it from memory/file (as the previous loading from the web should have saved it to memory/file). How do I implement this? I can get the loading from the web with a WebRequest object, but that's not enough to save it for later, faster, use.
WebRequest request = WebRequest.Create(imageURL);
Stream stream = request.GetResponse().GetResponseStream();
pictureBoxFirstPack.Image = Image.FromStream(stream);
I'm pretty sure you should be able to do this:
MemoryStream ms = new MemoryStream();
stream.CopyTo(ms);
Byte[] data = ms.ToArray();
Once you have it as a Byte array you can store it in a dictionary, a database, or wherever you like really.
Use the Image.Save method to save the downloaded image (follow an example from MSDN: http://msdn.microsoft.com/en-us/library/9t4syfhh.aspx)
// Construct a bitmap from the button image resource.
Bitmap bmp1 = new Bitmap(typeof(Button), "Button.bmp");
// Save the image as a GIF.
bmp1.Save("c:\\button.gif", System.Drawing.Imaging.ImageFormat.Gif);
One of the possible ways to check if the image already exists in your local storage is to calculate the hash-sum of every downloaded image and save it inside a dictionary
SHA256Managed sha = new SHA256Managed();
byte[] checksum = sha.ComputeHash(stream);
var hash = BitConverter.ToString(checksum).Replace("-", String.Empty);
// Store hash into a dictionary
You can use the WebClient to download file like this:
string fileNameLocally = #"c:\file.jpg";
using(WebClient client = new WebClient())
{
client.DownloadFile(imageURL, fileNameLocally);
//you can also use DownloadAsyncFile this methods do not block the calling thread.
}

Categories

Resources