Xamarin [RestSharp] + [Xam.Plugin.Media] upload model containing image - xamarin

I'm trying to upload an image from xamarin.forms and using restsharp for api service.
RestRequest uploadPostRestRequest = new RestRequest("post/create/", Method.POST);
uploadPostRestRequest.AddJsonBody(uploadPostRequest);
and this is my model UploadPostRequest
public class UploadPostRequest
{
public string content;
public byte[] image;
}
Question - Is it right to set image type as byte[]?
Would server accept this or would restsharp manage it?
If RestSharp has a nice control with this, can I just put MediaFile from Xam.Plugin.Media so I can upload it right over?
Xam.Plugin.Media is used for picking images from mobile device.
Too many options, so, that's why I'm looking for good advice.
Has anyone experienced this same issue before? please help.
For additional info, I cant use System.IO.File, Xamarin.Forms wont let me use it.

When the Xam.Plugin.Media finish loading the media either from the Camera or from the Library it returns a MediaFile. This object can be converter to a byte array with something like this:
byte[] byteArray;
using (var memoryStream = new MemoryStream ())
{
mediaFile.GetStream ().CopyTo (memoryStream);
mediaFile.Dispose ();
byteArray = memoryStream.ToArray ();
}
Now you have the byte array you just need to pass it to the method that will upload the image to your backend.

Related

Byte Image Rotation in .Net Core

I've an IFormFile image file (from postman as form data), which I convert into byte array. Before converting it into byte array, I want to rotate it into its actual position (if user input image as 90°(right). I'm implementing web api in asp.net core 2.0.
byte[] ImageBytes = Utils.ConvertFileToByteArray(model.Image);
public static byte[] ConvertFileToByteArray(IFormFile file)
{
using (var memoryStream = new MemoryStream())
{
file.CopyTo(memoryStream);
return memoryStream.ToArray();
}
}
Any help, Thanks in advance.
In my project I need to crop and resize the images users upload. And I am using a fantastic library called ImageSharp from Six Labors. You can use its image processor to do the transformation such as Resize, Crop, Skew, Rotate and more!
Install via NuGet
I am actually using their nightly build through MyGet.
Visual Studio -> Tools -> Options -> NuGet Package Manager -> Package Sources
Hit the "Plus" button to add a new package resource
I typed "ImageSharp Nightly" as the name and put "https://www.myget.org/F/sixlabors/api/v3/index.json" as the source url.
On Browse, search "SixLabors.ImageSharp" (In my case I also need "SixLabors.ImageSharp.Drawing" but in your case you might only need to core library. Always refer back to their documentations).
Crop & Resize
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Formats;
using SixLabors.ImageSharp.Processing;
using SixLabors.ImageSharp.Processing.Transforms;
using SixLabors.Primitives;
using System.IO;
namespace DL.SO.Project.Services.ImageProcessing.ImageSharp
{
public CropAndResizeResult CropAndResize(byte[] originalImage,
int offsetX, int offsetY, int croppedWidth, int croppedHeight,
int finalWidth, int finalHeight) : IImageProcessingService
{
IImageFormat format;
using (var image = Image.Load(originalImage, out format))
{
image.Mutate(x => x
// There is .Rotate() you can call for your case
.Crop(new Rectangle(offsetX, offsetY, croppedWidth, croppedHeight))
.Resize(finalWidth, finalHeight));
using (var output = new MemoryStream())
{
image.Save(output, format);
// This is just my custom class. But see you can easily
// get the processed image byte[] using the ToArray() method.
return new CropAndResizeResult
{
ImageExtension = format.Name,
CroppedImage = output.ToArray()
};
}
}
}
}
Hope this helps you - from a big fan of ImageSharp library!
Magick.NET, The ImageMagick wrapper for .Net Core can be used for many file manipulations, see https://github.com/dlemstra/Magick.NET
byte[] byt = System.IO.File.ReadAllBytes(filePath);
System.IO.MemoryStream ms = new System.IO.MemoryStream(byt);
using (Image img = Image.FromStream(ms))
{
RotateFlipType r = angle == 90 ? RotateFlipType.Rotate90FlipNone : RotateFlipType.Rotate270FlipNone;
img.RotateFlip(r);
img.Save(filePath);
}
Using your existing code you can do the following

Send an image rather than a link

I'm using the Microsoft Bot Framework with Cognitive Services to generate images from a source image that the user uploads via the bot. I'm using C#.
The Cognitive Services API returns a byte[] or a Stream representing the treated image.
How can I send that image directly to my user? All the docs and samples seem to point to me having to host the image as a publically addressable URL and send a link. I can do this but I'd rather not.
Does anyone know how to simple return the image, kind of like the Caption Bot does?
You should be able to use something like this:
var message = activity.CreateReply("");
message.Type = "message";
message.Attachments = new List<Attachment>();
var webClient = new WebClient();
byte[] imageBytes = webClient.DownloadData("https://placeholdit.imgix.net/~text?txtsize=35&txt=image-data&w=120&h=120");
string url = "data:image/png;base64," + Convert.ToBase64String(imageBytes)
message.Attachments.Add(new Attachment { ContentUrl = url, ContentType = "image/png" });
await _client.Conversations.ReplyToActivityAsync(message);
The image source of HTML image elements can be a data URI that contains the image directly rather than a URL for downloading the image. The following overloaded functions will take any valid image and encode it as a JPEG data URI string that may be provided directly to the src property of HTML elements to display the image. If you know ahead of time the format of the image returned, then you might be able to save some processing by not re-encoding the image as JPEG by just returning the image encoded as base 64 with the appropriate image data URI prefix.
public string ImageToBase64(System.IO.Stream stream)
{
// Create bitmap from stream
using (System.Drawing.Bitmap bitmap = System.Drawing.Bitmap.FromStream(stream) as System.Drawing.Bitmap)
{
// Save to memory stream as jpeg to set known format. Could also use PNG with changes to bitmap save
// and returned data prefix below
byte[] outputBytes = null;
using (System.IO.MemoryStream outputStream = new System.IO.MemoryStream())
{
bitmap.Save(outputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
outputBytes = outputStream.ToArray();
}
// Encoded image byte array and prepend proper prefix for image data. Result can be used as HTML image source directly
string output = string.Format("data:image/jpeg;base64,{0}", Convert.ToBase64String(outputBytes));
return output;
}
}
public string ImageToBase64(byte[] bytes)
{
using (System.IO.MemoryStream inputStream = new System.IO.MemoryStream())
{
inputStream.Write(bytes, 0, bytes.Length);
return ImageToBase64(inputStream);
}
}

How to extract text from image Android app

I am working on a feature for my Android app. I would like to read text from a picture then save that text in a database. Is using OCR the best way? Is there another way? Google suggests in its documentation that NDK should only be used if strictly necessary but what are the downfalls exactly?
Any help would be great.
you can use google vision library for convert image to text, it will give better output from image.
Add below library in build gradle:
compile 'com.google.android.gms:play-services-vision:10.0.0+'
TextRecognizer textRecognizer = new TextRecognizer.Builder(getApplicationContext()).build();
Frame imageFrame = new Frame.Builder()
.setBitmap(bitmap) // your image bitmap
.build();
String imageText = "";
SparseArray<TextBlock> textBlocks = textRecognizer.detect(imageFrame);
for (int i = 0; i < textBlocks.size(); i++) {
TextBlock textBlock = textBlocks.get(textBlocks.keyAt(i));
imageText = textBlock.getValue(); // return string
}
From this Simple example of OCRReader in Android tutorial you can read text from image and also you can scan for text using camera, using very simple code.
This library is developed using Mobile Vision Text API
For scan text from camera
OCRCapture.Builder(this)
.setUseFlash(true)
.setAutoFocus(true)
.buildWithRequestCode(CAMERA_SCAN_TEXT);
For extract text from image
String text = OCRCapture.Builder(this).getTextFromUri(pickedImage);
//You can also use getTextFromBitmap(Bitmap bitmap) or getTextFromImage(String imagePath) buplic APIs from OCRLibrary library.
Text from an image can be extracted using Firebase machine learning (ML) kit. There are two versions of the text recognition API, on-device API (free) and on-cloud API.
To use the API, first create BitMap of the image, which should be upright. Then create FirebaseVisionImage object passing the bitmap object.
FirebaseVisionImage image = FirebaseVisionImage.fromBitmap(bitmap);
Then create FirebaseVisionTextRecognizer object.
FirebaseVisionTextRecognizer textRecognizer = FirebaseVision.getInstance()
.getCloudTextRecognizer();
Then pass the FirebaseVisionImage object to processImage() method, add listeners to the resulting task and capture the extracted text in success callback method.
textRecognizer.processImage(image)
.addOnSuccessListener(new OnSuccessListener<FirebaseVisionText>() {
#Override
public void onSuccess(FirebaseVisionText firebaseVisionText) {
//process success
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
//process failure
}
});
For complete example which shows how to use Firebase ML text recognizer, see https://www.zoftino.com/extracting-text-from-images-android
There is a different option. You can upload your image to the server, OCR it from the server, then get the result.

Windows phone: what to do with webresponse object?

I am trying to create a simple rss feed reader. I got this webresponse object but how to extract text,links from this?
WebResponse response = request.EndGetResponse(result);
Also,can anyone tell me what is the underlying framework behind all the working of windows phone 8.Is it known as Silverlight?I want to know it so that I can make relevant Google searches and don't bother you people time and again?
It depends on what you want to do with it. You will need to get the Stream and then from there can turn it into a string (or other primitive type), just Json.Net to convert from json to an object, or you can use the stream to create an image.
using (var response = webRequest.EndGetResponse(asyncResult))
{
using (var reader = new StreamReader(response.GetResponseStream()))
{
// need a string?
string result = reader.ReadToEnd();
// Need to convert from json?
MyObject obj = Newtonsoft.Json.JsonConvert.DeserializeObject<MyObject>(result);
}
}

How to convert rad controls to images in silverlight

I'm using rad controls(charts and gridview) for developing an application,which i need to export the controls(each) into image.I have tried each control converting them into bytes format and send to webservice and converting them to images but sometime sending the byte data to service throws an error.Is any other way to convert each control into image.I have tried another way like.
Stream fileStream = File.OpenRead(#"\\HARAVEER-PC\TempImages\FlashPivot.png");
//PART 2 - use the stream to write the file output.
productChart.ExportToImage(fileStream, new Telerik.Windows.Media.Imaging.PngBitmapEncoder());
fileStream.Close();
It throwing me an error like cannot access to the folder TempImages.I have given sharing permissions to everyone but it doesn't access the folder.
Any solution is much appreciated.
private BitmapImage CreateChartImages()
{
Guid photoID = System.Guid.NewGuid();
string photolocation = #"D:\Temp\" + photoID.ToString() + ".jpg";
BitmapImage bi = new BitmapImage(new Uri(photolocation, UriKind.Absolute));
using (MemoryStream ms = new MemoryStream())
{
radChart.ExportToImage(ms, new PngBitmapEncoder());
bi.SetSource(ms);
}
return bi;
}

Resources