Redth / ZXing.Net.Mobile

Barcode Scanner for Xamarin.iOS, Xamarin.Android, UWP and Tizen
MIT License
1.07k stars 703 forks source link

ZXingBarcodeImageView Save Image to device #841

Open nikolaynn1984 opened 5 years ago

nikolaynn1984 commented 5 years ago

Hello, I need to save the result generated using

in jpeg format on the device. I searched for a lot of time on the Internet, I did not find the result. Can you help? Thanks in advance,
stesvis commented 5 years ago

I'd like to know this too!

iamprincejkc commented 3 years ago

Still no good info about this anywhere

nikolaynn1984 commented 3 years ago

Still no good info about this anywhere BUtton


private async void SaveButton_Clicked(object sender, EventArgs e)
{
try
{
var status = await CrossPermissions.Current.CheckPermissionStatusAsync(Permission.Storage);
if (status != PermissionStatus.Granted)
{
if (await CrossPermissions.Current.ShouldShowRequestPermissionRationaleAsync(Permission.Storage))
{
await DisplayAlert(LangResources.PermMessageName, LangResources.PermMessageStorage, "Ok");
}
var result = await CrossPermissions.Current.RequestPermissionsAsync(Permission.Storage);
status = result[Permission.Storage];
}
if (status == PermissionStatus.Granted)
{
if (!string.IsNullOrEmpty(EntGenerated.Text))
{
await DependencyService.Get<IBarcodeService>().SaveQRAsImage(EntGenerated.Text);
LblText.Text = LangResources.MessageSaved;
LblText.TextColor = Color.FromHex("#388e3c");
}
else
{
LblText.Text = LangResources.MessageEnter;
LblText.TextColor = Color.FromHex("#e53935");
}
            }
        }
        catch
        {
            LblText.Text = LangResources.MessageWrong;
            LblText.TextColor = Color.FromHex("#e53935");
        }

    }

private void GeneratedButton_Click(object sender, EventArgs e) {

        if (!string.IsNullOrEmpty(EntGenerated.Text))
        {
            try
            {
                var text = DateTime.Now.Ticks.ToString();
                GenerateView.Source = ImageSource.FromStream(() =>
                {
                    return DependencyService.Get<IBarcodeService>().ConvertImageStream(EntGenerated.Text, 300, 300);
                });
                LblText.Text = LangResources.MessageGenerated;
                LblText.TextColor = Color.FromHex("#388e3c");
                EntGenerated.PlaceholderColor = Color.Gray;

            }
            catch
            {
                LblText.Text = LangResources.MessageWrong;
                LblText.TextColor = Color.FromHex("#e53935");
            }
        }
        else
        {
            LblText.Text = LangResources.MessageEnter;
            EntGenerated.PlaceholderColor = Color.FromHex("#e53935");
        }

    }
Interface
public interface IBarcodeService
{
    Stream ConvertImageStream(string text, int width, int height);
    Task<string> SaveQRAsImage(string text);
}
Android
   [assembly: Xamarin.Forms.Dependency(typeof(BarcodeService))]

namespace ScanReader.Droid { public class BarcodeService : IBarcodeService {

    public Stream ConvertImageStream(string text, int width, int height)
    {
        var barcodeWriter = new ZXing.Mobile.BarcodeWriter
        {
            Format = ZXing.BarcodeFormat.QR_CODE,
            Options = new ZXing.Common.EncodingOptions
            {
                Width = width,
                Height = height,
                Margin = 5
            }
        };

        barcodeWriter.Renderer = new ZXing.Mobile.BitmapRenderer();
        var bitmap = barcodeWriter.Write(text);
        var stream = new MemoryStream();
        bitmap.Compress(Bitmap.CompressFormat.Png, 100, stream);
        stream.Position = 0;
        return stream;
    }

    TaskCompletionSource<string> SaveQRComplete = null;
    public Task<string> SaveQRAsImage(string text)
    {
        // if(ContextCompat.CheckSelfPermission(this. Manifest))
        SaveQRComplete = new TaskCompletionSource<string>();
        try
        {
            var barcodeWriter = new ZXing.Mobile.BarcodeWriter
            {
                Format = ZXing.BarcodeFormat.QR_CODE,
                Options = new ZXing.Common.EncodingOptions
                {
                    Width = 1000,
                    Height = 1000,
                    Margin = 2,
                }
            };

            barcodeWriter.Renderer = new ZXing.Mobile.BitmapRenderer();
            var bitmap = barcodeWriter.Write(text);
            var stream = new MemoryStream();
            bitmap.Compress(Bitmap.CompressFormat.Png, 100, stream);  // this is the diff between iOS and Android
            stream.Position = 0;

            byte[] imageData = stream.ToArray();

            var dir = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDcim);
            var pictures = dir.AbsolutePath;
            //adding a time stamp time file name to allow saving more than one image... otherwise it overwrites the previous saved image of the same name
            string name = "Code" + System.DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".jpg";
            string filePath = System.IO.Path.Combine(pictures, name);

            System.IO.File.WriteAllBytes(filePath, imageData);
            //mediascan adds the saved image into the gallery
            var mediaScanIntent = new Intent(Intent.ActionMediaScannerScanFile);
            mediaScanIntent.SetData(Android.Net.Uri.FromFile(new Java.IO.File(filePath)));

            Android.App.Application.Context.SendBroadcast(mediaScanIntent);
            SaveQRComplete.SetResult(filePath);
            return SaveQRComplete.Task;
        }
        catch (System.Exception e)
        {
            System.Console.WriteLine(e.ToString());
            return null;
        }
    }
}

}

iOS

[assembly: Dependency(typeof(BarcodeService))] namespace ScanReader.iOS { public class BarcodeService : IBarcodeService { public Stream ConvertImageStream(string text, int width, int height) { var barcodeWriter = new ZXing.Mobile.BarcodeWriter { Format = ZXing.BarcodeFormat.QR_CODE, Options = new ZXing.Common.EncodingOptions { Width = width, Height = height, Margin = 10 } }; barcodeWriter.Renderer = new ZXing.Mobile.BitmapRenderer(); var bitmap = barcodeWriter.Write(text); var stream = bitmap.AsPNG().AsStream();
stream.Position = 0;

        return stream;
    }

    public Task<string> SaveQRAsImage(string text)
    {
        TaskCompletionSource<string> SaveQRComplete = new TaskCompletionSource<string>();
        try
        {
            var barcodeWriter = new ZXing.Mobile.BarcodeWriter
            {
                Format = ZXing.BarcodeFormat.QR_CODE,
                Options = new ZXing.Common.EncodingOptions
                {
                    Width = 1000,
                    Height = 1000,
                    Margin = 10
                }
            };

            barcodeWriter.Renderer = new ZXing.Mobile.BitmapRenderer();
            var bitmap = barcodeWriter.Write(text);
            var stream = bitmap.AsPNG().AsStream();

            byte[] imageData = bitmap.AsPNG().ToArray();

            var chartImage = new UIImage(NSData.FromArray(imageData));
            chartImage.SaveToPhotosAlbum((image, error) =>
            {

                if (error != null)
                {
                    Console.WriteLine(error.ToString());
                }

            });
            SaveQRComplete.SetResult("true");

        }
        catch
        {
            SaveQRComplete.SetResult("false");
        }
        return SaveQRComplete.Task;
    }
}

}

PetrVobornik commented 3 years ago

Yes please, I need this function too. I want to share PNG file with QR code (by Xamarin.Essentials.ShareFile). Primary on UWP and Android.