Ejemplo n.º 1
0
 private void SaveAsImage(Stream stream, int width, int height, Bitmap.CompressFormat format)
 {
     int[] data = new int[width * height];
     GetData(data);
     // internal structure is BGR while bitmap expects RGB
     for (int i = 0; i < data.Length; ++i)
     {
         uint pixel = (uint)data[i];
         data[i] = (int)((pixel & 0xFF00FF00) | ((pixel & 0x00FF0000) >> 16) | ((pixel & 0x000000FF) << 16));
     }
     using (Bitmap bitmap = Bitmap.CreateBitmap(width, height, Bitmap.Config.Argb8888))
     {
         bitmap.SetPixels(data, 0, width, 0, 0, width, height);
         bitmap.Compress(format, 100, stream);
         bitmap.Recycle();
     }
 }
Ejemplo n.º 2
0
        async Task<byte[]> GetImageAsByteAsync(Bitmap.CompressFormat format, int quality, int desiredWidth, int desiredHeight)
        {
            if (Control == null)
                return null;

            var drawable = Control.Drawable as BitmapDrawable;

            if (drawable == null || drawable.Bitmap == null)
                return null;

            Bitmap bitmap = drawable.Bitmap;

            if (desiredWidth != 0 || desiredHeight != 0)
            {
                double widthRatio = (double)desiredWidth / (double)bitmap.Width;
                double heightRatio = (double)desiredHeight / (double)bitmap.Height;

                double scaleRatio = Math.Min(widthRatio, heightRatio);

                if (desiredWidth == 0)
                    scaleRatio = heightRatio;

                if (desiredHeight == 0)
                    scaleRatio = widthRatio;

                int aspectWidth = (int)((double)bitmap.Width * scaleRatio);
                int aspectHeight = (int)((double)bitmap.Height * scaleRatio);

                bitmap = Bitmap.CreateScaledBitmap(bitmap, aspectWidth, aspectHeight, true);
            }

            using (var stream = new MemoryStream())
            {
                await bitmap.CompressAsync(format, quality, stream).ConfigureAwait(false);
                var compressed = stream.ToArray();

                if (desiredWidth != 0 || desiredHeight != 0)
                {
                    bitmap.Recycle();
                    bitmap.TryDispose();
                }

                return compressed;
            }
        }
Ejemplo n.º 3
0
        public static byte[] RenderAsImage(this View view, Bitmap.CompressFormat format, int quality = 100)
        {
            byte[] imageBytes = null;

            using (var bitmap = Render(view))
            {
                if (bitmap != null)
                {
                    imageBytes = bitmap.AsImageBytes(format, quality);
                    if (!bitmap.IsRecycled)
                    {
                        bitmap.Recycle();
                    }
                }
            }

            return(imageBytes);
        }
Ejemplo n.º 4
0
        public async Task <string> ConvertImage(string imagenFilePath, int quality, FormatoImagen formatoImagen)
        {
            if (string.IsNullOrWhiteSpace(imagenFilePath))
            {
                throw new ArgumentNullException("File path de la imagen a convertir esta vacio!.");
            }
            if (formatoImagen == FormatoImagen.SinTipoFormato)
            {
                throw new ArgumentNullException("Formato de imagen invalido!.");
            }

            string uniqueID = UUID.RandomUUID().ToString();

            using (Java.IO.File path = BaseAndroid.OS.Environment.GetExternalStoragePublicDirectory(BaseAndroid.OS.Environment.DirectoryPictures))
                using (Java.IO.File file = new Java.IO.File(path, uniqueID + ".jpg"))
                    using (FileStream fileOutputStream = new FileStream(file.AbsolutePath, FileMode.CreateNew))
                    {
                        Bitmap imageToConvert = await BitmapFactory.DecodeFileAsync(imagenFilePath);

                        Bitmap.CompressFormat compressFormat = null;
                        if (formatoImagen == FormatoImagen.Jpeg)
                        {
                            compressFormat = Bitmap.CompressFormat.Jpeg;
                        }
                        else if (formatoImagen == FormatoImagen.Png)
                        {
                            compressFormat = Bitmap.CompressFormat.Png;
                        }

                        await imageToConvert.CompressAsync(compressFormat, quality, fileOutputStream);

                        await fileOutputStream.FlushAsync();

                        fileOutputStream.Close();
                        fileOutputStream.Dispose();

                        return(file.AbsolutePath);
                    }
        }
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            RequestWindowFeature(Android.Views.WindowFeatures.NoTitle);
            SetContentView(Resource.Layout.cropimage);

            imageView = FindViewById <CropImageView>(Resource.Id.image);

            showStorageToast(this);

            Bundle extras = Intent.Extras;

            if (extras != null)
            {
                imagePath = extras.GetString("image-path");

                saveUri = getImageUri(imagePath);
                if (extras.GetString(MediaStore.ExtraOutput) != null)
                {
                    saveUri = getImageUri(extras.GetString(MediaStore.ExtraOutput));
                }

                bitmap = getBitmap(imagePath);

                aspectX = extras.GetInt("aspectX");
                aspectY = extras.GetInt("aspectY");
                outputX = extras.GetInt("outputX");
                outputY = extras.GetInt("outputY");
                scale   = extras.GetBoolean("scale", true);
                scaleUp = extras.GetBoolean("scaleUpIfNeeded", true);

                if (extras.GetString("outputFormat") != null)
                {
                    outputFormat = Bitmap.CompressFormat.ValueOf(extras.GetString("outputFormat"));
                }
            }

            if (bitmap == null)
            {
                Finish();
                return;
            }

            Window.AddFlags(WindowManagerFlags.Fullscreen);


            FindViewById <Button>(Resource.Id.cancel).Click += (sender, e) =>
            {
                CropImageServiceAndroid.SetResult(new CropResult(false)
                {
                    Message = "Cancelled"
                });
                Finish();
                return;
            };
            FindViewById <Button>(Resource.Id.done).Click += (sender, e) => { OnSaveClicked(); };

            FindViewById <Button>(Resource.Id.rotateLeft).Click += (o, e) =>
            {
                bitmap = Util.rotateImage(bitmap, -90);
                RotateBitmap rotateBitmap = new RotateBitmap(bitmap);
                imageView.SetImageRotateBitmapResetBase(rotateBitmap, true);
                addHighlightView();
            };

            //FindViewById<Button>(Resource.Id.rotateRight).Click += (o, e) =>
            //{
            //    bitmap = Util.rotateImage(bitmap, 90);
            //    RotateBitmap rotateBitmap = new RotateBitmap(bitmap);
            //    imageView.SetImageRotateBitmapResetBase(rotateBitmap, true);
            //    addHighlightView();
            //};

            imageView.SetImageBitmapResetBase(bitmap, true);
            addHighlightView();
        }
Ejemplo n.º 6
0
 public virtual RequestBuilder EncodeFormat(Bitmap.CompressFormat format) => (RequestBuilder)EncodeFormat_T(format);
Ejemplo n.º 7
0
 public virtual RequestOptions EncodeFormat(Bitmap.CompressFormat format) => (RequestOptions)EncodeFormat_T(format);
Ejemplo n.º 8
0
        private static void SaveFromMemory(PixelBuffer[] pixelBuffers, int count, ImageDescription description, Stream imageStream, Bitmap.CompressFormat imageFormat)
        {
            var colors = pixelBuffers[0].GetPixels <int>();

            using (var bitmap = Bitmap.CreateBitmap(description.Width, description.Height, Bitmap.Config.Argb8888))
            {
                var pixelData  = bitmap.LockPixels();
                var sizeToCopy = colors.Length * sizeof(int);

                unsafe
                {
                    fixed(int *pSrc = colors)
                    {
                        // Copy the memory
                        if (description.Format == PixelFormat.R8G8B8A8_UNorm || description.Format == PixelFormat.R8G8B8A8_UNorm_SRgb)
                        {
                            CopyMemoryBGRA(pixelData, (IntPtr)pSrc, sizeToCopy);
                        }
                        else if (description.Format == PixelFormat.B8G8R8A8_UNorm || description.Format == PixelFormat.B8G8R8A8_UNorm_SRgb)
                        {
                            Utilities.CopyMemory(pixelData, (IntPtr)pSrc, sizeToCopy);
                        }
                        else
                        {
                            throw new NotSupportedException(string.Format("Pixel format [{0}] is not supported", description.Format));
                        }
                    }
                }

                bitmap.UnlockPixels();
                bitmap.Compress(imageFormat, 100, imageStream);
            }
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Saves the specified color data as an image with the specified format.
        /// </summary>
        /// <param name="data">An array containing the image's color data.</param>
        /// <param name="width">The width of the image in pixels.</param>
        /// <param name="height">The height of the image in pixels.</param>
        /// <param name="stream">The stream to which to save the image data.</param>
        /// <param name="format">The format with which to save the image.</param>
        private unsafe void Save(Color[] data, Int32 width, Int32 height, Stream stream, Bitmap.CompressFormat format)
        {
            using (var bmp = Bitmap.CreateBitmap(width, height, Bitmap.Config.Argb8888))
            {
                var bmpData = bmp.LockPixels();

                fixed(Color *pData = data)
                {
                    for (int y = 0; y < height; y++)
                    {
                        var pSrc = pData + (y * width);
                        var pDst = ((Byte *)bmpData + (y * bmp.RowBytes));

                        for (int x = 0; x < width; x++)
                        {
                            var color  = *pSrc++;
                            *   pDst++ = color.R;
                            *   pDst++ = color.G;
                            *   pDst++ = color.B;
                            *   pDst++ = color.A;
                        }
                    }
                }

                bmp.UnlockPixels();
                bmp.Compress(format, 100, stream);
            }
        }
Ejemplo n.º 10
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            RequestWindowFeature(WindowFeatures.NoTitle);
            SetContentView(Resource.Layout.cropimage);

            _imageView = FindViewById <CropImageView>(Resource.Id.image);

            ShowStorageToast(this);

            var extras = Intent.Extras;

            if (extras != null)
            {
                _imagePath = extras.GetString("image-path");

                _saveUri = GetImageUri(_imagePath);
                if (extras.GetString(MediaStore.ExtraOutput) != null)
                {
                    _saveUri = GetImageUri(extras.GetString(MediaStore.ExtraOutput));
                }

                _bitmap = GetBitmap(_imagePath);

                _aspectX = extras.GetInt("aspectX");
                _aspectY = extras.GetInt("aspectY");
                _outputX = extras.GetInt("outputX");
                _outputY = extras.GetInt("outputY");
                _scale   = extras.GetBoolean("scale", true);
                _scaleUp = extras.GetBoolean("scaleUpIfNeeded", true);

                if (extras.GetString("outputFormat") != null)
                {
                    _outputFormat = Bitmap.CompressFormat.ValueOf(extras.GetString("outputFormat"));
                }
            }

            if (_bitmap == null)
            {
                Finish();
                //raise event
                MediaCroped?.Invoke(this, new XViewEventArgs(nameof(MediaCroped), null));
                return;
            }

            Window.AddFlags(WindowManagerFlags.Fullscreen);


            FindViewById <Button>(Resource.Id.discard).Click += (sender, e) => { OnDisCardClick(); };
            FindViewById <Button>(Resource.Id.save).Click    += (sender, e) => { OnSaveClicked(); };

            FindViewById <Button>(Resource.Id.rotateLeft).Click += (o, e) =>
            {
                _bitmap = Util.RotateImage(_bitmap, -90);
                var rotateBitmap = new RotateBitmap(_bitmap);
                _imageView.SetImageRotateBitmapResetBase(rotateBitmap, true);
                AddHighlightView();
            };

            FindViewById <Button>(Resource.Id.rotateRight).Click += (o, e) =>
            {
                _bitmap = Util.RotateImage(_bitmap, 90);
                var rotateBitmap = new RotateBitmap(_bitmap);
                _imageView.SetImageRotateBitmapResetBase(rotateBitmap, true);
                AddHighlightView();
            };

            _imageView.SetImageBitmapResetBase(_bitmap, true);
            AddHighlightView();
        }
Ejemplo n.º 11
0
        private static void SaveFromMemory(PixelBuffer[] pixelBuffers, int count, ImageDescription description, Stream imageStream, Bitmap.CompressFormat imageFormat)
        {
            var colors = pixelBuffers[0].GetPixels <int>();

            using (var bitmap = Bitmap.CreateBitmap(colors, description.Width, description.Height, Bitmap.Config.Argb8888))
            {
                bitmap.Compress(imageFormat, 0, imageStream);
            }
        }
Ejemplo n.º 12
0
 public async static Task <bool> WriteBitmapTo(System.IO.Stream st, Bitmap bmp, Bitmap.CompressFormat format, int quality = 70)
 {
     return(await bmp.CompressAsync(format, quality, st));
 }
Ejemplo n.º 13
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            RequestWindowFeature(Android.Views.WindowFeatures.NoTitle);
            SetContentView(Resource.Layout.cropimage);

            imageView = FindViewById <CropImageView>(Resource.Id.image);

            showStorageToast(this);

            Bundle extras = Intent.Extras;

            if (extras != null)
            {
                imagePath = extras.GetString("image-path");

                saveUri = getImageUri(imagePath);
                if (extras.GetString(MediaStore.ExtraOutput) != null)
                {
                    saveUri = getImageUri(extras.GetString(MediaStore.ExtraOutput));
                }

                bitmap = getBitmap(imagePath);

                aspectX = extras.GetInt("aspectX");
                aspectY = extras.GetInt("aspectY");
                outputX = extras.GetInt("outputX");
                outputY = extras.GetInt("outputY");
                scale   = extras.GetBoolean("scale", true);
                scaleUp = extras.GetBoolean("scaleUpIfNeeded", true);

                if (extras.GetString("outputFormat") != null)
                {
                    outputFormat = Bitmap.CompressFormat.ValueOf(extras.GetString("outputFormat"));
                }
            }

            if (bitmap == null)
            {
                Finish();
                return;
            }

            Window.AddFlags(WindowManagerFlags.Fullscreen);


            FindViewById <Button>(Resource.Id.discard).Click += (sender, e) => { SetResult(Result.Canceled); Finish(); };
            //FindViewById<Button>(Resource.Id.save).Click += async delegate { onSaveClicked(); };

            FindViewById <Button>(Resource.Id.save).Click += async delegate {
                if (Saving)
                {
                    return;
                }

                Saving = true;

                var r = Crop.CropRect;

                int width  = r.Width();
                int height = r.Height();

                Bitmap croppedImage = Bitmap.CreateBitmap(width, height, Bitmap.Config.Rgb565);
                {
                    Canvas canvas  = new Canvas(croppedImage);
                    Rect   dstRect = new Rect(0, 0, width, height);
                    canvas.DrawBitmap(bitmap, r, dstRect, null);
                }

                // If the output is required to a specific size then scale or fill
                if (outputX != 0 && outputY != 0)
                {
                    if (scale)
                    {
                        // Scale the image to the required dimensions
                        Bitmap old = croppedImage;
                        croppedImage = Util.transform(new Matrix(),
                                                      croppedImage, outputX, outputY, scaleUp);
                        if (old != croppedImage)
                        {
                            old.Recycle();
                        }
                    }
                    else
                    {
                        // Don't scale the image crop it to the size requested.
                        // Create an new image with the cropped image in the center and
                        // the extra space filled.
                        Bitmap b = Bitmap.CreateBitmap(outputX, outputY,
                                                       Bitmap.Config.Rgb565);
                        Canvas canvas = new Canvas(b);

                        Rect srcRect = Crop.CropRect;
                        Rect dstRect = new Rect(0, 0, outputX, outputY);

                        int dx = (srcRect.Width() - dstRect.Width()) / 2;
                        int dy = (srcRect.Height() - dstRect.Height()) / 2;

                        // If the srcRect is too big, use the center part of it.
                        srcRect.Inset(Math.Max(0, dx), Math.Max(0, dy));

                        // If the dstRect is too big, use the center part of it.
                        dstRect.Inset(Math.Max(0, -dx), Math.Max(0, -dy));

                        // Draw the cropped bitmap in the center
                        canvas.DrawBitmap(bitmap, srcRect, dstRect, null);

                        // Set the cropped bitmap as the new bitmap
                        croppedImage.Recycle();
                        croppedImage = b;
                    }
                }

                // Return the cropped image directly or save it to the specified URI.
                Bundle myExtras = Intent.Extras;

                if (myExtras != null &&
                    (myExtras.GetParcelable("data") != null || myExtras.GetBoolean("return-data")))
                {
                    Bundle extrasas = new Bundle();
                    extras.PutParcelable("data", croppedImage);
                    SetResult(Result.Ok,
                              (new Intent()).SetAction("inline-data").PutExtras(extrasas));
                    Finish();
                }
                else
                {
                    //Toast.MakeText(Application.Context, saveUri.ToString(), ToastLength.Long).Show();
                    //Toast.MakeText(Application.Context, "Upload Complete", ToastLength.Long).Show();

                    //Upload to Azure
                    ISQLiteConnection connacc = null;

                    ISQLiteConnectionFactory factoryacc = new MvxDroidSQLiteConnectionFactory();

                    var    sqlitediracc      = new Java.IO.File(global::Android.OS.Environment.GetExternalStoragePublicDirectory(global::Android.OS.Environment.DirectoryPictures), "Boruto");
                    string filenameactionacc = sqlitediracc.Path + "/mysqlitesas.db";

                    connacc = factoryacc.Create(filenameactionacc);
                    connacc.CreateTable <Azurecon>();
                    var useridconnc = "";
                    foreach (var eu in connacc.Table <Azurecon>().Where(eu => eu.Sastring == "using"))
                    {
                        useridconnc = eu.UserId;
                    }
                    connacc.Close();
                    //myuserid = "115708452302383620142";
                    useridconnc = useridconnc.Replace("@", "");
                    useridconnc = useridconnc.Replace(".", "");
                    var myurl    = "http://93.118.34.239:8888/" + useridconnc;
                    Uri azureuri = new Uri(myurl);


                    HttpWebRequest request = new HttpWebRequest(azureuri);
                    request.Method = "GET";


                    HttpWebResponse response = request.GetResponse() as HttpWebResponse;
                    try
                    {
                        using (StreamReader sr = new StreamReader(response.GetResponseStream()))
                        {
                            string responseString = sr.ReadToEnd();
                            Toast.MakeText(this, saveUri.ToString(), ToastLength.Short).Show();
                            try
                            {
                                await UseContainerSAS(responseString, saveUri.ToString());
                            }
                            catch
                            {
                            }
                        }
                    }
                    catch {
                    }
                    //End Upload to Azure

                    Bitmap b = croppedImage;
                    BackgroundJob.StartBackgroundJob(this, null, "Saving image", () => saveOutput(b), mHandler);
                }
            };

            FindViewById <Button>(Resource.Id.rotateLeft).Click += (o, e) =>
            {
                bitmap = Util.rotateImage(bitmap, -90);
                RotateBitmap rotateBitmap = new RotateBitmap(bitmap);
                imageView.SetImageRotateBitmapResetBase(rotateBitmap, true);
                addHighlightView();
            };

            FindViewById <Button>(Resource.Id.rotateRight).Click += (o, e) =>
            {
                bitmap = Util.rotateImage(bitmap, 90);
                RotateBitmap rotateBitmap = new RotateBitmap(bitmap);
                imageView.SetImageRotateBitmapResetBase(rotateBitmap, true);
                addHighlightView();
            };

            imageView.SetImageBitmapResetBase(bitmap, true);
            addHighlightView();
        }
Ejemplo n.º 14
0
 public static void compress(this Bitmap bitmap, Bitmap.CompressFormat format, int quality, System.IO.Stream stream)
 {
     bitmap.Compress(format, quality, stream);
 }
Ejemplo n.º 15
0
        public async Task DeleteTransparencyFromAnImage(string imagenFilePath, int quality, FormatoImagen formatoImagen)
        {
            if (string.IsNullOrWhiteSpace(imagenFilePath))
            {
                throw new ArgumentNullException("File path de la imagen a convertir esta vacio!.");
            }
            if (formatoImagen == FormatoImagen.SinTipoFormato)
            {
                throw new ArgumentNullException("Formato de imagen invalido!.");
            }

            Bitmap sourceBitmap = await BitmapFactory.DecodeFileAsync(imagenFilePath);

            int minX = sourceBitmap.Width;
            int minY = sourceBitmap.Height;
            int maxX = -1;
            int maxY = -1;

            for (int y = 0; y < sourceBitmap.Height; y++)
            {
                for (int x = 0; x < sourceBitmap.Width; x++)
                {
                    int alpha = (sourceBitmap.GetPixel(x, y) >> 24) & 255;
                    if (alpha > 0)   // pixel is not 100% transparent
                    {
                        if (x < minX)
                        {
                            minX = x;
                        }
                        if (x > maxX)
                        {
                            maxX = x;
                        }
                        if (y < minY)
                        {
                            minY = y;
                        }
                        if (y > maxY)
                        {
                            maxY = y;
                        }
                    }
                }
            }
            if ((maxX < minX) || (maxY < minY))
            {
                return; // Bitmap is entirely transparent
            }
            // crop bitmap to non-transparent area and return:
            Bitmap bitmapWithoutTransparency = Bitmap.CreateBitmap(sourceBitmap, minX, minY, (maxX - minX) + 1, (maxY - minY) + 1);

            using (var stream = new FileStream(imagenFilePath, FileMode.Create))
            {
                Bitmap.CompressFormat compressFormat = null;
                if (formatoImagen == FormatoImagen.Jpeg)
                {
                    compressFormat = Bitmap.CompressFormat.Jpeg;
                }
                else if (formatoImagen == FormatoImagen.Png)
                {
                    compressFormat = Bitmap.CompressFormat.Png;
                }

                await bitmapWithoutTransparency.CompressAsync(compressFormat, quality, stream);

                stream.Close();
            }
        }
Ejemplo n.º 16
0
        public Stream ResizeImage(
            Stream imageStream,
            double width,
            double height,
            string format = "jpeg",
            int quality   = 96)
        {
            // Decode stream
            var options = new BitmapFactory.Options {
                InJustDecodeBounds = true
            };

            BitmapFactory.DecodeStream(imageStream, null, options);
            imageStream.Seek(0, SeekOrigin.Begin);

            var width0  = options.OutWidth;
            var height0 = options.OutHeight;

            // No need to resize
            if ((height >= height0) && (width >= width0))
            {
                return(imageStream);
            }

            // Calculate scale and sample size
            var scale = Math.Min(width / width0, height / height0);

            width  = width0 * scale;
            height = height0 * scale;

            var inSampleSize = 1;

            while ((0.5 * height0 > inSampleSize * height) &&
                   (0.5 * width0 > inSampleSize * width))
            {
                inSampleSize *= 2;
            }

            // Resize
            var originalImage = BitmapFactory.DecodeStream(imageStream, null,
                                                           new BitmapFactory.Options {
                InJustDecodeBounds = false,
                InSampleSize       = inSampleSize
            });
            Bitmap resizedImage = Bitmap.CreateScaledBitmap(
                originalImage, (int)(width), (int)(height), false);

            originalImage.Recycle();

            // Compress
            var stream = new MemoryStream();

            Bitmap.CompressFormat imageFormat = (format == "png") ?
                                                Bitmap.CompressFormat.Png :
                                                Bitmap.CompressFormat.Jpeg;
            resizedImage.Compress(imageFormat, quality, stream);
            resizedImage.Recycle();

            // Reset stream and return
            stream.Seek(0, SeekOrigin.Begin);
            return(stream);
        }