MAUI image crop example and display it - c#

I need to crop and display an image using ImageCropper.MAUI, I can't get the image to show up and I get image not found exception.
https://github.com/jbowmanp1107/ImageCropper.Maui
I have added code where I can get the image path after cropped.
ImageCrop.Success = (imageFile) =>
{
Application.Current.Dispatcher.Dispatch(async () =>
{
imageFile = imageFile.Replace(#"/my_images/Pictures/", "");
var _d = FileSystem.Current.AppDataDirectory;
var pathTemp = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyPictures), imageFile);
//"/my_images/Pictures/cropped2795616814194734447.png"
//cropped2795616814194734447.png
//cropped9006441269099458689.png
if (File.Exists(pathTemp))
{
//Check for file exists or not
}
path = pathTemp;
resultImage.Source = ImageSource.FromFile(pathTemp);
await Empty();
});
}
I have also attached the path of image as below in emulator.
Image path in emulator

Related

How can i convert a file .png to a Bitmap? Nothing works for me. Error "'Failed to decode image. The provided image must be a Bitmap.'" Xamarin.forms

I'm working with Xamarin in the part of Xamarin.Forms i need to convert a file ("image.png") to a Bitmap because when project run its enter in "break mode" and show me this message "Java.Lang.IllegalArgumentException: 'Failed to decode image. The provided image must be a Bitmap.'". So i tried to convert the file in many ways like:
1_ Using methods from System.Drawing.Bitmap but it's show this exception "This operation is not supported in this platform"
2_ Cannot use Android.Graphics because i'm working in xamarin.forms not in xamarin.android.
3_ I tried to convert the "image.png" into a base64 or byte[] array and then into a bitmap but the problem is the same like in first problem because to convert from byte[] array or base64 to a Bitmap i have use methods from System.Drawing.Bitmap.
4_ I tried using the library SkiaSharp but i don't have success because i don't found so much information about how to convert .png to SKBitmap and then convert SKBitmap to Bitmap (even i don't know if this is possible).
5_ Finally i converted "image.png" to a "image.bmp" with an app and use the file .bmp in my project but it doesn't work too.
the "image.png" i have to save in a string variable, well that's the idea.
If you have a solution with SkiaSharp o whatever i will glad
EDIT
here is a part of my code, i just save in a variable the image
Icon = "pin_blue.png";
//i can't use a path because in xamarin you have many size from the same
//image for the different size of the screen
EDIT 2 This is my method to show the pins in google maps
private void ShowPins(List<PointsOfInterest> resultPointsOfInterest)
{
if (resultPointsOfInterest != null && resultPointsOfInterest.Any())
{
var location = Geolocation.GetLastKnownLocationAsync();
PointsOfInterest position = new PointsOfInterest();
if (location != null)
{
position.ccsm0166latitud = location.Result.Latitude;
position.ccsm0166longitud = location.Result.Longitude;
}
else {
position = resultPointsOfInterest.First();
}
//Distance = Distance.FromKilometers(new Random().Next(23,35));
Distance = Distance.FromKilometers(3);
Position = new Position(position.ccsm0166latitud, position.ccsm0166longitud);
PinsFiltered= Pins = new List<PinCustom>(resultPointsOfInterest.Select(
x => new PinCustom()
{
Position =
new Position(x.ccsm0166latitud, x.ccsm0166longitud),
Address = x.ccsm0166direccion,
Label = x.ccsm0166nombre,
Type = PinType.Place,
TypePointOfInterest = x.ccsm0166tipositio,
IconBM = Int32.Parse(x.ccsm0166tipositio) == (int)PointOfInterestType.branch ? PinCustom.ConvertToBitmap("pin_blue.png") :
Int32.Parse(x.ccsm0166tipositio) == (int)PointOfInterestType.branch ? "pin_blue.png" :
Int32.Parse(x.ccsm0166tipositio) == (int)PointOfInterestType.branchWithExtendedHours ? "pin_black.png" :
Int32.Parse(x.ccsm0166tipositio) == (int)PointOfInterestType.branchWithExtendedHours2 ? "pin_black.png" :
Int32.Parse(x.ccsm0166tipositio) == (int)PointOfInterestType.branchWithExtendedHours3 ? "pin_black.png" :
Int32.Parse(x.ccsm0166tipositio) == (int)PointOfInterestType.selfServiceTerminal ? "pin_green.png" :
Int32.Parse(x.ccsm0166tipositio) == (int)PointOfInterestType.atmServBox ? "pin_yellow.png" : string.Empty
}).ToList());
}
else
{
Pins = new List<PinCustom>();
}
}
This is the class Pin where i save the image
public class PinCustom : Pin
{
public string TypePointOfInterest { get; set; }
public string Icon { get; set; }
public Bitmap { get; set; }
//Here i create this variable to save a bitmap but i don't know if i do the things well
}
this is the icon .png i want to show in googlemaps
Pin Blue Image
To open your file and convert it to byte array:
string directory = Path.Combine(Android.OS.Environment.ExternalStorageDirectory.AbsolutePath, Android.OS.Environment.DirectoryDownloads);
// or your image directory, just replace it
var stream = File.OpenWrite(Path.Combine(directory, "image.png"));
byte[] buff = ConvertStreamToByteArray(stream);
stream.Close();
public static byte[] ConvertStreamToByteArray(Stream stream)
{
byte[] byteArray = new byte[16 * 1024];
using (MemoryStream mStream = new MemoryStream())
{
int bit;
while ((bit = stream.Read(byteArray, 0, byteArray.Length)) > 0)
{
mStream.Write(byteArray, 0, bit);
}
return mStream.ToArray();
}
}
then, to pass this byte array to SKBitmap:
SKBitmap bmp = SKBitmap.Decode(buff);
EDIT:
If you want to try without ConvertStreamToByteArray():
byte[] buff = null;
stream.Write(buff, 0, buff.Length);
This Write will depend of the type of your stream. In this example, I'm using FileStream.
EDIT 2:
string resourceID = "image.png";
Assembly assembly = GetType().GetTypeInfo().Assembly;
using (Stream stream = assembly.GetManifestResourceStream(resourceID))
{
resourceBitmap = SKBitmap.Decode(stream);
SKBitmap bmp = SKImage.FromBitmap(resourceBitmap);
}
and then you can use this bitmap to draw and fill your SKCanvas:
canvas.DrawBitmap(bmp, 0, 0);
Use ffmpeg
command for this: ffmpeg -i image.png image.bmp
i have 5 types of pins (pins are the image .png) when i put the pins
in format .png
if you want to custom the pins in your map, you can simply use Custom Renderers to achieve this.
The icon used to represent a marker can be customized by calling the MarkerOptions.SetIcon method. This can be accomplished by overriding the CreateMarker method, which is invoked for each Pin that's added to the map:
protected override MarkerOptions CreateMarker(Pin pin)
{
var marker = new MarkerOptions();
marker.SetPosition(new LatLng(pin.Position.Latitude, pin.Position.Longitude));
marker.SetTitle(pin.Label);
marker.SetSnippet(pin.Address);
marker.SetIcon(BitmapDescriptorFactory.FromResource(Resource.Drawable.pin));
return marker;
}
If you want to display different icons, you can refer to the following code:
protected override MarkerOptions CreateMarker(Pin pin)
{
var marker = new MarkerOptions();
marker.SetPosition(new LatLng(pin.Position.Latitude, pin.Position.Longitude));
marker.SetTitle(pin.Label);
marker.SetSnippet(pin.Address);
var customPin = (Element as CustomMap).CustomPins.FirstOrDefault(p => p.Position == pin.Position);
if (customPin != null)
{
if (customPin.IconType == "corporate")
{
marker.SetIcon(BitmapDescriptorFactory.FromResource(Resource.Drawable.corporate));
}
else if (customPin.IconType == "pickup")
{
marker.SetIcon(BitmapDescriptorFactory.FromResource(Resource.Drawable.bus));
}
}
return marker;
}
For more, check:Customizing the Marker.

Saving Canvas to device memory in Xamarin.Forms

I have canvas made from bitMap (photo) and my finger drawings in Xamarin Forms. I need to save it to memory device (perfectly it would be photo roll but could be just memory of device). For now (after googling few hours) i have something like this:
saveButt.Clicked += async(sender, args) =>
{
var newSurface = SKSurface.Create(
(int)canvasView.CanvasSize.Width,
(int)canvasView.CanvasSize.Height,
SKImageInfo.PlatformColorType,
SKAlphaType.Premul);
var canvas = newSurface.Canvas;
if (photoBitmap != null)
{
canvas.DrawBitmap(photoBitmap, new SKRect(0, 0, (float) canvasView.Width, (float) canvasView.Height));
}
foreach (SKPath path in completedPaths)
{
canvas.DrawPath(path, paint);
}
foreach (SKPath path in inProgressPaths.Values)
{
canvas.DrawPath(path, paint);
}
canvas.Flush();
var snap = newSurface.Snapshot();
var pngImage = snap.Encode();
};
I don't know how i can get access to memory or photo roll to save it.
#Edit
I tried use PCLStorage plugin to save it and for now it don't throw any exceptions or errors but still when i look through all folders i can't find any new folder or file with those names.
var snap = newSurface.Snapshot();
var pngImage = snap.Encode();
IFolder rootFolder = FileSystem.Current.LocalStorage;
IFolder folder = await rootFolder.CreateFolderAsync("MySubFolder",
CreationCollisionOption.OpenIfExists);
IFile file = await folder.CreateFileAsync("image.png",
CreationCollisionOption.ReplaceExisting);
using (Stream s = await file.OpenAsync(PCLStorage.FileAccess.ReadAndWrite))
{
pngImage.SaveTo(s);
}

WIA Duplex scanning using document feeder

Below is my c# code trying to transfer image from the duplex scanner. I'm able to acquire one image (Front Only) but i cant get the second image. I have tried changing the device property 3088 to 5 but i get a catastrophic failure. I'm working with WIA 2.0 on windows 10, 64 bit but project is using X86. I have also tried to transfer the image twice as i have read in previous questions but i get an error. I'm using duplexid600 scanner and from the windows scanner software i'm able to get a duplex image. Below is my code
CommonDialogClass commonDialogClass = new CommonDialogClass();
Device scannerDevice = commonDialogClass.ShowSelectDevice(WiaDeviceType.ScannerDeviceType, false, false);
if (scannerDevice != null)
{
Item scannnerItem = scannerDevice.Items[1];
//object value;
// AdjustScannerSettings(scannnerItem, 300, 0, 0, 1010, 620, 0, 0);
// object kuku;
// kuku = scannerDevice.Properties["Document Handling Select"].get_Value();
scannerDevice.Properties["Document Handling Select"].set_Value(1);//3088
// kuku = scannerDevice.Properties["Document Handling Select"].get_Value();
scannerDevice.Properties["Pages"].set_Value(1);//3096
// object scanResult = commonDialogClass.ShowTransfer(scannnerItem, WIA.FormatID.wiaFormatTIFF, false);
object scanResult = scannnerItem.Transfer(WIA.FormatID.wiaFormatBMP);
//object scanResult1 = scannnerItem.Transfer(WIA.FormatID.wiaFormatTIFF);
if (scanResult != null)
{
ImageFile image = (ImageFile) scanResult;
// string fileName = Path.GetTempPath() + DateTime.Now.ToString("dd-MM-yyyy-hh-mm-ss-fffffff") + ".tif";
var imageBytes = (byte[])image.FileData.get_BinaryData();
var ms = new MemoryStream(imageBytes);
var img = Image.FromStream(ms);
//int pageCount = 0;
//Image Tiff = img;
//pageCount = Tiff.GetFrameCount(FrameDimension.Page);
// Tiff.Dispose();
// SaveImageToPNGFile(image, fileName);
pictureBoxScannedImage.Image = img;
}
}
Call this one twice, it should give the 2nd image if you have 3088 set to 5 (duplex).
object scanResult = scannnerItem.Transfer(WIA.FormatID.wiaFormatBMP);
object scanResultbacksite = scannnerItem.Transfer(WIA.FormatID.wiaFormatBMP);
Beware though - on my scanner with the 2nd "start scan" command, you issue a new task, meaning your scanner could start to scan the 2nd physical page already - while assigning the backpage to your file. If you know a solution to this, tell me please!

QRCode Extraction With ZXing

Hi I'm trying to read QRCode from scanned images, but I'm getting a low index of extraction (19 extracted from 500 images) the code of extraction:
class QrExtractor
{
public String extractFrom(Bitmap image)
{
using (image)
{
LuminanceSource source;
source = new BitmapLuminanceSource(image);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
Result result = new QRCodeReader().decode(bitmap);
if (result != null)
{
return result.Text;
}
return "Couldn't Extract";
}
}
}
Is there any improvements that I can apply to this?
Thanks

Convert StorageFile to WriteableBitmap WP8.1 Silverlight

I am developing this application where I am able to get all the pictures from picture library as StorageFile data type. now I want to change it to writeablebitmap, apply a sketch filter and show in image control. can someone please help me in changing the data type from StorageFile to writeablebitmap?
here is my code:
StorageFolderpicturesFolder = KnownFolders.PicturesLibrary;
IReadOnlyList<IStorageFile> file = await picturesFolder.GetFilesAsync(CommonFileQuery.OrderByDate);
if(file.Count > 0)
{
foreach(StorageFile f in file)
{
// the code for changing the data type will go here
}
This code works for me.
if (file.Count > 0)
{
foreach (StorageFile f in file)
{
ImageProperties properties = await f.Properties.GetImagePropertiesAsync();
WriteableBitmap bmp = new WriteableBitmap((int)properties.Width, (int)properties.Height);
bmp.SetSource((await f.OpenReadAsync()).AsStream());
// Ready to go with bmp
}
}
Try this, it should work:
IReadOnlyList<IStorageFile> files = await picturesFolder.GetFilesAsync(CommonFileQuery.OrderByDate);
if(files.Count > 0)
{
var images = new List<WriteableBitmap>();
foreach(var f in files)
{
var bitmap = new WriteableBitmap(500, 500);
using (var stream = await f.OpenAsync(FileAccessMode.ReadWrite))
{
bitmap.SetSource(stream);
}
images.Add(bitmap);
}
}

Categories

Resources