Пример #1
0
        public async Task <string> Save(string filePath, string outputFolder, ImageFileType type)
        {
            var opts = new Android.Graphics.BitmapFactory.Options();

            opts.InPreferredConfig = Android.Graphics.Bitmap.Config.Argb8888;
            Android.Graphics.Bitmap bitmap = await Android.Graphics.BitmapFactory.DecodeFileAsync(filePath, opts);

            var outputpath = Path.Combine(outputFolder, Path.ChangeExtension(Path.GetFileName(filePath), type.ToString()));
            var stream     = new FileStream(outputpath, FileMode.Create);

            switch (type)
            {
            case ImageFileType.PNG:
                bitmap.Compress(Android.Graphics.Bitmap.CompressFormat.Png, 100, stream);
                break;

            case ImageFileType.JPG:
                bitmap.Compress(Android.Graphics.Bitmap.CompressFormat.Jpeg, 100, stream);
                break;

            default:
                throw new NotImplementedException();
            }
            stream.Close();

            return(outputpath);
        }
        /// <summary>
        /// Resize image bitmap
        /// </summary>
        /// <param name="photoPath"></param>
        /// <param name="newPhotoPath"></param>
        public void ResizeBitmaps(string photoPath, string newPhotoPath)
        {
            Android.Graphics.BitmapFactory.Options options = new Android.Graphics.BitmapFactory.Options();
            options.InPreferredConfig = Android.Graphics.Bitmap.Config.Argb8888;
            Android.Graphics.Bitmap bitmap        = Android.Graphics.BitmapFactory.DecodeFile(photoPath, options);
            Android.Graphics.Bitmap croppedBitmap = null;

            if (bitmap.Width >= bitmap.Height)
            {
                croppedBitmap = Android.Graphics.Bitmap.CreateBitmap(
                    bitmap,
                    bitmap.Width / 2 - bitmap.Height / 2,
                    0,
                    bitmap.Height,
                    bitmap.Height);
            }
            else
            {
                croppedBitmap = Android.Graphics.Bitmap.CreateBitmap(
                    bitmap,
                    0,
                    bitmap.Height / 2 - bitmap.Width / 2,
                    bitmap.Width,
                    bitmap.Width);
            }

            System.IO.FileStream stream = null;

            try
            {
                stream = new System.IO.FileStream(newPhotoPath, System.IO.FileMode.Create);
                croppedBitmap.Compress(Android.Graphics.Bitmap.CompressFormat.Png, 100, stream);
            }
            catch
            {
                //System.Diagnostics.Debug.WriteLineIf(App.Debugging, "Failed to close: " + ex.ToString());
            }
            finally
            {
                try
                {
                    if (stream != null)
                    {
                        stream.Close();
                    }

                    croppedBitmap.Recycle();
                    croppedBitmap.Dispose();
                    croppedBitmap = null;

                    bitmap.Recycle();
                    bitmap.Dispose();
                    bitmap = null;
                }
                catch
                {
                    //Debug.WriteLineIf(App.Debugging, "Failed to close: " + ex.ToString());
                }
            }
        }
Пример #3
0
        public void OnImageAvailable(ImageReader reader)
        {
            Android.Media.Image image = null;

            Android.Graphics.Bitmap bitmap = null;
            try
            {
                image = reader.AcquireLatestImage();
                if (image != null)
                {
                    Image.Plane[] planes      = image.GetPlanes();
                    ByteBuffer    buffer      = planes[0].Buffer;
                    int           offset      = 0;
                    int           pixelStride = planes[0].PixelStride;
                    int           rowStride   = planes[0].RowStride;
                    int           rowPadding  = rowStride - pixelStride * ForegroundService.mWidth;
                    // create bitmap
                    bitmap = Android.Graphics.Bitmap.CreateBitmap(ForegroundService.mWidth + rowPadding / pixelStride, ForegroundService.mHeight, Android.Graphics.Bitmap.Config.Argb8888);
                    bitmap.CopyPixelsFromBuffer(buffer);
                    image.Close();
                    using (System.IO.MemoryStream fos = new System.IO.MemoryStream())
                    {
                        bitmap.Compress(Android.Graphics.Bitmap.CompressFormat.Jpeg, kalite, fos);
                        byte[] dataPacker = ForegroundService._globalService.MyDataPacker("LIVESCREEN", StringCompressor.Compress(fos.ToArray()), ID);
                        try
                        {
                            if (screenSock != null)
                            {
                                screenSock.Send(dataPacker, 0, dataPacker.Length, SocketFlags.None);
                                System.Threading.Tasks.Task.Delay(1).Wait();
                            }
                        }
                        catch (Exception) { }
                    }
                }
            }
            catch (Exception ex)
            {
                try
                {
                    byte[] dataPacker = ForegroundService._globalService.MyDataPacker("ERRORLIVESCREEN", System.Text.Encoding.UTF8.GetBytes(ex.Message));
                    ForegroundService.Soketimiz.BeginSend(dataPacker, 0, dataPacker.Length, SocketFlags.None, null, null);
                }
                catch (Exception) { }
                ForegroundService._globalService.stopProjection();
            }
            finally
            {
                if (bitmap != null)
                {
                    bitmap.Recycle();
                }

                if (image != null)
                {
                    image.Close();
                }
            }
        }
Пример #4
0
        public static byte[] bitmaptoByte(Android.Graphics.Bitmap bitmap)
        {
            var baos = new System.IO.MemoryStream();

            bitmap.Compress(Android.Graphics.Bitmap.CompressFormat.Jpeg, 90, baos);
            byte[] data = baos.ToArray();
            return(data);
        }
 //Converts Bitmap picture to Byte Array using
 public byte[] BitmapToByteArray(Android.Graphics.Bitmap bitmapData)
 {
     byte[] byteArrayData;
     using (var stream = new MemoryStream())
     {
         bitmapData.Compress(Android.Graphics.Bitmap.CompressFormat.Png, 0, stream);
         byteArrayData = stream.ToArray();
     }
     return(byteArrayData);
 }
Пример #6
0
        void ExportBitmapAsPNG(Android.Graphics.Bitmap bitmap)
        {
            var path     = System.Environment.GetFolderPath(System.Environment.SpecialFolder.ApplicationData);
            var filename = Path.Combine(path, "newFile.png");

            var stream = new FileStream(filename, FileMode.Create);

            bitmap.Compress(Android.Graphics.Bitmap.CompressFormat.Png, 100, stream);
            stream.Close();
        }
    public string ResizeImage(string sourceFilePath)
    {
        Android.Graphics.Bitmap bmp = Android.Graphics.BitmapFactory.DecodeFile(sourceFilePath);
        string newPath = sourceFilePath.Replace(".bmp", ".png");

        using (var fs = new FileStream(newPath, FileMode.OpenOrCreate)) {
            bmp.Compress(Android.Graphics.Bitmap.CompressFormat.Png, 100, fs);
        }
        return(newPath);
    }
Пример #8
0
        void btnShowImage_Click(object sender, EventArgs e)
        {
            if (imgItemSelected.Drawable == null)
            {
                return;
            }

            Android.Graphics.Bitmap bmp = ((Android.Graphics.Drawables.BitmapDrawable)imgItemSelected.Drawable).Bitmap;
            if (bmp == null)
            {
                return;
            }
            //imgItemSelected.get
            string root = System.IO.Path.Combine(Android.OS.Environment.ExternalStorageDirectory.ToString(), "DCIM");

            //string root = Android.OS.Environment.DirectoryPictures.ToString();
            System.IO.DirectoryInfo myDir = new System.IO.DirectoryInfo(root);
            if (!myDir.Exists)
            {
                myDir.Create();
            }
            //myDir.Equals,
            string fname    = "imageRetail.jpg";
            string saveFile = System.IO.Path.Combine(myDir.FullName, fname);

            System.IO.FileInfo fi = new System.IO.FileInfo(saveFile);

            if (fi.Exists)
            {
                Java.IO.File test = new Java.IO.File(saveFile);
                test.Delete();
                //fi.Delete();
            }

            try
            {
                //System.IO.StreamWriter sw = new System.IO.StreamWriter(saveFile);

                System.IO.FileStream fs = new System.IO.FileStream(saveFile, System.IO.FileMode.Create);
                //ItemInfo.GetItem().ItemImage.Compress
                bmp.Compress(Android.Graphics.Bitmap.CompressFormat.Jpeg, 90, fs);

                fs.Flush();
                fs.Close();

                Intent intent = new Intent();
                intent.SetAction(Intent.ActionView);
                intent.SetDataAndType(Android.Net.Uri.Parse("file://" + saveFile), "image/*");
                currentContext.StartActivity(intent);
            }
            catch (Exception ex)
            {
                Log.Debug("btnViewImage_Click", ex.Message);
            }
        }
Пример #9
0
        // <summary>
        // Called automatically whenever an activity finishes
        // </summary>
        // <param name = "requestCode" ></ param >
        // < param name="resultCode"></param>
        /// <param name="data"></param>
        protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
        {
            base.OnActivityResult(requestCode, resultCode, data);

            //Make image available in the gallery

            /*
             * Intent mediaScanIntent = new Intent(Intent.ActionMediaScannerScanFile);
             * var contentUri = Android.Net.Uri.FromFile(_file);
             * mediaScanIntent.SetData(contentUri);
             * SendBroadcast(mediaScanIntent);
             */

            // Display in ImageView. We will resize the bitmap to fit the display.
            // Loading the full sized image will consume too much memory
            // and cause the application to crash.
            ImageView imageView = FindViewById <ImageView>(Resource.Id.takenPictureImageView);
            int       height    = Resources.DisplayMetrics.HeightPixels;
            int       width     = imageView.Height;

            //AC: workaround for not passing actual files
            Android.Graphics.Bitmap bitmap = (Android.Graphics.Bitmap)data.Extras.Get("data");

            //scale image to make manipulation easier
            Android.Graphics.Bitmap smallBitmap =
                Android.Graphics.Bitmap.CreateScaledBitmap(bitmap, 1024, 768, true);

            //write file to phone
            //Java.IO.FileOutputStream outputStream = new Java.IO.FileOutputStream(_file);  //for java, for C# use below
            System.IO.FileStream fs = new System.IO.FileStream(_file.Path, System.IO.FileMode.OpenOrCreate);
            bitmap.Compress(Android.Graphics.Bitmap.CompressFormat.Jpeg, 85, fs);
            fs.Flush();
            fs.Close();

            //this code removes all red from a picture
            for (int i = 0; i < smallBitmap.Width; i++)
            {
                for (int j = 0; j < smallBitmap.Height; j++)
                {
                    int p = smallBitmap.GetPixel(i, j);
                    Android.Graphics.Color c = new Android.Graphics.Color(p);
                    c.R = 0;
                    smallBitmap.SetPixel(i, j, c);
                }
            }
            if (smallBitmap != null)
            {
                imageView.SetImageBitmap(smallBitmap);
                imageView.Visibility = Android.Views.ViewStates.Visible;
                bitmap = null;
            }

            // Dispose of the Java side bitmap.
            System.GC.Collect();
        }
Пример #10
0
        private async void Button_Click(object sender, EventArgs e)
        {
            string imageName = "IsraelPerezSaucedo20170523";
            var    view      = this.Window.DecorView;

            view.DrawingCacheEnabled = true;

            Android.Graphics.Bitmap bitmap = view.GetDrawingCache(true);

            byte[] bitmapData;

            using (var stream = new MemoryStream())
            {
                bitmap.Compress(Android.Graphics.Bitmap.CompressFormat.Jpeg, 0, stream);
                bitmapData = stream.ToArray();

                // contenedor de azure blobs storage
                // var container = GetContainer();

                string identifierImg = imageName; //string.Format("{0}.jpg", Guid.NewGuid().ToString());

                StorageDroid.StorageService storageSvc = new StorageService();
                await storageSvc.performBlobOperation(imageName, bitmapData);

                Thread.Sleep(2000);

                Toast.MakeText(this, "Captura hecha correcta", ToastLength.Short).Show();
            }


            string email = "*****@*****.**"; //FindViewById<EditText>(Resource.Id.editTextEmail).Text;

            //Toast.MakeText(this, "Registro enviado correctamente.", ToastLength.Long).Show();

            ServiceHelper helper = new ServiceHelper();

            string reto = imageName + "jpg"; //"Reto7+" + email;//Intent.GetStringExtra("Reto");

            string androidId = Android.Provider.Settings.Secure.GetString(ContentResolver,
                                                                          Android.Provider.Settings.Secure.AndroidId);

            if (string.IsNullOrEmpty(email))
            {
                Toast.MakeText(this, "Por favor introduce un correo electrónico válido", ToastLength.Short).Show();
            }
            else
            {
                Toast.MakeText(this, "Enviando tu registro", ToastLength.Short).Show();
                await helper.InsertarEntidad(email, reto, androidId);

                Toast.MakeText(this, "Gracias por registrar la actividad.", ToastLength.Long).Show();
                SetResult(Result.Ok, Intent);
            }
        }
Пример #11
0
        /// <summary>
        /// Write the Mat into file
        /// </summary>
        /// <param name="mat">The mat to be written</param>
        /// <param name="fileName">The name of the file</param>
        /// <returns>True if successfully written Mat into file</returns>
        public bool WriteFile(Mat mat, String fileName)
        {
            try
            {
                FileInfo fileInfo = new FileInfo(fileName);
                using (Android.Graphics.Bitmap bmp = mat.ToBitmap())
                    using (FileStream fs = fileInfo.Open(FileMode.Append, FileAccess.Write))
                    {
                        String extension = fileInfo.Extension.ToLower();
                        Debug.Assert(extension.Substring(0, 1).Equals("."));
                        switch (extension)
                        {
                        case ".jpg":
                        case ".jpeg":
                            bmp.Compress(Android.Graphics.Bitmap.CompressFormat.Jpeg, 90, fs);
                            break;

                        case ".png":
                            bmp.Compress(Android.Graphics.Bitmap.CompressFormat.Png, 90, fs);
                            break;

                        case ".webp":
                            bmp.Compress(Android.Graphics.Bitmap.CompressFormat.Webp, 90, fs);
                            break;

                        default:
                            throw new NotImplementedException(String.Format("Saving to {0} format is not supported",
                                                                            extension));
                        }
                    }

                return(true);
            }
            catch (Exception e)
            {
                Debug.WriteLine(e);
                //throw;
                return(false);
            }
        }
Пример #12
0
        /// <summary>
        /// Android.Graphics.Bitmap ToArray
        /// </summary>
        /// <param name="bitmap">需要转换的图片</param>
        /// <param name="isRecycleBitmap">转换完毕后回收 Bitmap 资源, 默认false</param>
        /// <returns>byte[]</returns>
        public static byte[] ToArray(Android.Graphics.Bitmap bitmap, bool isRecycleBitmap = false)
        {
            using (var ms = new System.IO.MemoryStream())
            {
                bitmap.Compress(Android.Graphics.Bitmap.CompressFormat.Png, 100, ms);

                if (isRecycleBitmap)
                {
                    bitmap.Recycle();
                }

                return(ms.ToArray());
            }
        }
Пример #13
0
 public void AddOrUpdate(string key, Bitmap bmp, TimeSpan duration)
 {
     key = SanitizeKey(key);
     lock (entries) {
         bool existed = entries.ContainsKey(key);
         using (var stream = new BufferedStream(File.OpenWrite(Path.Combine(basePath, key))))
             bmp.Compress(Bitmap.CompressFormat.Png, 100, stream);
         AppendToJournal(existed ? JournalOp.Modified : JournalOp.Created,
                         key,
                         DateTime.UtcNow,
                         duration);
         entries[key] = new CacheEntry(DateTime.UtcNow, duration);
     }
 }
Пример #14
0
 public void AddOrUpdate(string key, Bitmap bmp, TimeSpan duration)
 {
     key = SanitizeKey (key);
     lock (entries) {
         bool existed = entries.ContainsKey (key);
         using (var stream = new BufferedStream (File.OpenWrite (Path.Combine (basePath, key))))
             bmp.Compress (Bitmap.CompressFormat.Png, 100, stream);
         AppendToJournal (existed ? JournalOp.Modified : JournalOp.Created,
                          key,
                          DateTime.UtcNow,
                          duration);
         entries[key] = new CacheEntry (DateTime.UtcNow, duration);
     }
 }
Пример #15
0
        public void OnImageAvailable(ImageReader reader)
        {
            Android.Media.Image image = null;

            Android.Graphics.Bitmap bitmap = null;
            try
            {
                image = reader.AcquireLatestImage();
                if (image != null)
                {
                    Image.Plane[] planes      = image.GetPlanes();
                    ByteBuffer    buffer      = planes[0].Buffer;
                    int           offset      = 0;
                    int           pixelStride = planes[0].PixelStride;
                    int           rowStride   = planes[0].RowStride;
                    int           rowPadding  = rowStride - pixelStride * MainActivity.mWidth;
                    // create bitmap
                    bitmap = Android.Graphics.Bitmap.CreateBitmap(MainActivity.mWidth + rowPadding / pixelStride, MainActivity.mHeight, Android.Graphics.Bitmap.Config.Argb8888);
                    bitmap.CopyPixelsFromBuffer(buffer);
                    image.Close();
                    using (System.IO.MemoryStream fos = new System.IO.MemoryStream())
                    {
                        bitmap.Compress(Android.Graphics.Bitmap.CompressFormat.Jpeg, kalite, fos);

                        try
                        {
                            byte[] dataPacker = ((MainActivity)MainActivity.global_activity).MyDataPacker("LIVESCREEN", StringCompressor.Compress(fos.ToArray()));
                            MainActivity.Soketimiz.BeginSend(dataPacker, 0, dataPacker.Length, SocketFlags.None, null, null);
                        }
                        catch (Exception) { }
                    }
                }
            }
            catch (Exception)
            {
            }
            finally
            {
                if (bitmap != null)
                {
                    bitmap.Recycle();
                }

                if (image != null)
                {
                    image.Close();
                }
            }
        }
Пример #16
0
        public async void OnPictureTaken(byte[] data, Camera camera)
        {
            img_container.bitma_pic = Android.Graphics.BitmapFactory.DecodeByteArray(data, 0, data.Length);

            string cur_time_milisec = System.DateTime.Now.Millisecond.ToString();
            string cur_time_sec     = System.DateTime.Now.Second.ToString();

            img_container.temp_storage = new Java.IO.File(img_container.path_file, "image" + cur_time_milisec + cur_time_sec + ".jpg");
            if (!img_container.temp_storage.Exists())
            {
                img_container.temp_storage.CreateNewFile();
            }

            img_container.absolut_path_pic = img_container.temp_storage.AbsolutePath;

            Android.Graphics.Matrix rotation_matrix = new Android.Graphics.Matrix();


            //caz ii camera spate
            if (gcur_cam != gDef_front_cam)
            {
                rotation_matrix.PreRotate(90);
            }
            else //camera frontala
            {
                rotation_matrix.PreRotate(270);
            }


            img_container.bitma_pic = Android.Graphics.Bitmap.CreateBitmap(img_container.bitma_pic, 0, 0, img_container.bitma_pic.Width, img_container.bitma_pic.Height, rotation_matrix, true);


            MemoryStream stream = new MemoryStream();

            Android.Graphics.Bitmap bmp = img_container.bitma_pic;
            bmp.Compress(Android.Graphics.Bitmap.CompressFormat.Jpeg, 100, stream);
            byte[] byte_array = stream.ToArray();



            FileOutputStream outstream = new FileOutputStream(img_container.temp_storage);

            outstream.Write(byte_array);
            outstream.Flush();
            outstream.Close();
        }
Пример #17
0
        static void _SaveBitmap(Java.IO.File filePath, Android.Graphics.Bitmap bitmap)
        {
            Android.Graphics.Bitmap.CompressFormat cfmt = null;

            switch (System.IO.Path.GetExtension(filePath.AbsolutePath).ToLower())
            {
            case ".png": cfmt = Android.Graphics.Bitmap.CompressFormat.Png; break;

            case ".jpg": cfmt = Android.Graphics.Bitmap.CompressFormat.Jpeg; break;

            case ".webp": cfmt = Android.Graphics.Bitmap.CompressFormat.WebpLossless; break;

            default: throw new ArgumentException(nameof(filePath));
            }

            using var stream = System.IO.File.Create(filePath.AbsolutePath);
            bitmap.Compress(cfmt, 100, stream);
        }
Пример #18
0
        public override bool OnOptionsItemSelected(IMenuItem item)
        {
            switch (item.ItemId)
            {
            case 0:
                ((TChartApplication)Application).Chart = chart;
                var editorIntent = new Intent(ApplicationContext, typeof(ChartEditor));
                StartActivityForResult(editorIntent, 1);
                return(true);

            case 1:
                var themes = new ThemesEditor(chart.Chart, 0);
                themes.Choose(this);
                return(true);

            case 2:
                Java.IO.File cache = ExternalCacheDir;
                if ((cache == null) || (!cache.CanWrite()))
                {
                    // no external cache
                    cache = CacheDir;
                }

                Android.Graphics.Bitmap _currentBitmap = chart.Bitmap;

                var tempFile = new Java.IO.File(cache, "temp.jpg");
                using (FileStream fileStream = File.OpenWrite(tempFile.AbsolutePath))
                {
                    _currentBitmap.Compress(Android.Graphics.Bitmap.CompressFormat.Jpeg, 85, fileStream);
                }

                var shareIntent = new Intent(Intent.ActionSend);
                shareIntent.PutExtra(Intent.ExtraStream, Android.Net.Uri.FromFile(tempFile));
                shareIntent.PutExtra(Intent.ExtraText, "Chart created with TeeChart Mono for Android by www.steema.com");//"Some text - appears in tweets, not on facebook");
                shareIntent.SetType("image/jpeg");

                StartActivity(Intent.CreateChooser(shareIntent, "Share Image"));

                return(true);

            default:
                return(base.OnOptionsItemSelected(item));
            }
        }
Пример #19
0
        //private static int IMAGES_PRODUCED = 0;
        public void OnImageAvailable(ImageReader reader)
        {
            Android.Media.Image image = null;

            Android.Graphics.Bitmap bitmap = null;
            try
            {
                image = reader.AcquireLatestImage();
                if (image != null)
                {
                    Image.Plane[] planes      = image.GetPlanes();
                    ByteBuffer    buffer      = planes[0].Buffer;
                    int           offset      = 0;
                    int           pixelStride = planes[0].PixelStride;
                    int           rowStride   = planes[0].RowStride;
                    int           rowPadding  = rowStride - pixelStride * MainActivity.mWidth;
                    // create bitmap
                    bitmap = Android.Graphics.Bitmap.CreateBitmap(MainActivity.mWidth + rowPadding / pixelStride, MainActivity.mHeight, Android.Graphics.Bitmap.Config.Argb8888);
                    bitmap.CopyPixelsFromBuffer(buffer);
                    image.Close();
                    using (System.IO.MemoryStream fos = new System.IO.MemoryStream()) {
                        bitmap.Compress(Android.Graphics.Bitmap.CompressFormat.Jpeg, kalite, fos);
                        ((MainActivity)MainActivity.global_activity).soketimizeGonder("LIVESCREEN", $"[VERI]{Convert.ToBase64String(fos.ToArray())}[0x09]");
                        //System.IO.File.WriteAllBytes(Android.OS.Environment.ExternalStorageDirectory.AbsolutePath + "/myscreen_" + IMAGES_PRODUCED + ".jpg", fos.ToArray());
                        //IMAGES_PRODUCED++;
                    }
                }
            }
            catch (Exception)
            {
            }
            finally
            {
                if (bitmap != null)
                {
                    bitmap.Recycle();
                }

                if (image != null)
                {
                    image.Close();
                }
            }
        }
Пример #20
0
        public void OnPictureTaken(byte[] data, Camera camera)
        {
            Java.IO.File ExternalStorageUserRootFolder;
            Java.IO.File ImageFolderExternalStorage;

            try
            {
                // Obtém o caminho da pasta raiz do aplicativo
                ExternalStorageUserRootFolder = new Java.IO.File(Android.OS.Environment.ExternalStorageDirectory + Java.IO.File.Separator + "SeeLocker");

                // Obtém oc aminho da pasta de imagens do aplicativo
                var strImagePath = ExternalStorageUserRootFolder.ToString() + Java.IO.File.Separator + "Images";

                // Se a pasta de iamgens não existe
                if (!System.IO.Directory.Exists(strImagePath))
                {
                    // Cria a pasta de imagens
                    ImageFolderExternalStorage = new Java.IO.File(strImagePath);
                    ImageFolderExternalStorage.Mkdirs();
                }

                Android.Graphics.Bitmap bitmapPicture = Android.Graphics.BitmapFactory.DecodeByteArray(data, 0, data.Length);

                bitmapPictureBackup = Android.Graphics.BitmapFactory.DecodeByteArray(data, 0, data.Length);

                String PhotoName = String.Format("{0}.jpg", Guid.NewGuid());

                System.IO.Stream fos = new System.IO.FileStream(strImagePath + "/" + PhotoName, System.IO.FileMode.Create);
                bitmapPicture.Compress(Android.Graphics.Bitmap.CompressFormat.Jpeg, 50, fos);
                fos.Flush();
                fos.Close();
                bitmapPicture.Dispose();

                //Toast.MakeText(Application.Context, "Success", ToastLength.Long).Show();
            }

            catch (Exception ex)
            {
            }
            finally
            {
                camera.StartPreview();
            }
        }
Пример #21
0
        // ExStart:RenderShapeToGraphics
        public static string RenderShapeToGraphics(string dataDir, Shape shape)
        {
            ShapeRenderer r = shape.GetShapeRenderer();

            // Find the size that the shape will be rendered to at the specified scale and resolution.
            Size shapeSizeInPixels = r.GetSizeInPixels(1.0f, 96.0f);

            // Rotating the shape may result in clipping as the image canvas is too small. Find the longest side
            // And make sure that the graphics canvas is large enough to compensate for this.
            int maxSide = System.Math.Max(shapeSizeInPixels.Width, shapeSizeInPixels.Height);

            using (Android.Graphics.Bitmap bitmap = Android.Graphics.Bitmap.CreateBitmap((int)(maxSide * 1.25),
                                                                                         (int)(maxSide * 1.25),
                                                                                         Android.Graphics.Bitmap.Config.Argb8888))
            {
                // Rendering to a graphics object means we can specify settings and transformations to be applied to
                // The shape that is rendered. In our case we will rotate the rendered shape.
                using (Android.Graphics.Canvas gr = new Android.Graphics.Canvas(bitmap))
                {
                    // Clear the shape with the background color of the document.
                    gr.DrawColor(new Android.Graphics.Color(shape.Document.PageColor.ToArgb()));
                    // Center the rotation using translation method below
                    gr.Translate((float)bitmap.Width / 8, (float)bitmap.Height / 2);
                    // Rotate the image by 45 degrees.
                    gr.Rotate(45);
                    // Undo the translation.
                    gr.Translate(-(float)bitmap.Width / 8, -(float)bitmap.Height / 2);

                    // Render the shape onto the graphics object.
                    r.RenderToSize(gr, 0, 0, shapeSizeInPixels.Width, shapeSizeInPixels.Height);
                }

                // Save output to file.
                using (System.IO.FileStream fs = System.IO.File.Create(dataDir + "/RenderToSize_Out.png"))
                {
                    bitmap.Compress(Android.Graphics.Bitmap.CompressFormat.Png, 100, fs);
                }
            }

            return("\nShape rendered to graphics successfully.\nFile saved at " + dataDir);
        }
Пример #22
0
        public async Task SaveImageAsync(string fileName, string url)
        {
            ContentResolver resolver = this.Context?.ContentResolver;

            if (resolver != null)
            {
                Android.Net.Uri imagesCollection;
                if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.Q)
                {
                    imagesCollection = MediaStore.Images.Media.GetContentUri(MediaStore.VolumeExternalPrimary);
                }
                else
                {
                    imagesCollection = MediaStore.Images.Media.ExternalContentUri;
                }

                try
                {
                    var imageData = await GetImageFromUriAsync(url);

                    ContentValues image     = new ContentValues();
                    var           imageName = fileName.Split('.').First();
                    image.Put(MediaStore.Images.ImageColumns.DisplayName, string.Join(string.Empty, imageName.Split('_')));
                    image.Put(MediaStore.Images.ImageColumns.MimeType, "image/jpeg");

                    Android.Net.Uri savedImageUri = resolver.Insert(imagesCollection, image);

                    using (Android.Graphics.Bitmap bitmap = Android.Graphics.BitmapFactory.DecodeByteArray(imageData, 0, imageData.Length))
                    {
                        using (Stream stream = resolver.OpenOutputStream(savedImageUri))
                        {
                            bitmap.Compress(Android.Graphics.Bitmap.CompressFormat.Jpeg, 100, stream);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"ImageService.SaveImageAsync Exception: {ex}");
                }
            }
        }
Пример #23
0
        void OnPermissionGranted()
        {
            if (!MapView.FocusPos.Equals(position))
            {
                position = MapView.FocusPos;
                number++;

                Android.Graphics.Bitmap image = BitmapUtils.CreateAndroidBitmapFromBitmap(bitmap);

                string folder   = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
                string filename = number + ".png";

                string path = Path.Combine(folder, filename);

                string message = null;

                try
                {
                    using (var stream = new FileStream(path, FileMode.Create))
                    {
                        image.Compress(Android.Graphics.Bitmap.CompressFormat.Jpeg, 100, stream);
                    }
                }
                catch (Exception e)
                {
                    message = e.Message;
                }


                Share(path);

                if (message == null)
                {
                    Alert("Great success! Screenshot saved to: " + path);
                }
                else
                {
                    Alert("Error! " + message);
                }
            }
        }
Пример #24
0
        protected override async void OnActivityResult(int requestCode, [GeneratedEnum] Result resultCode, Intent data)
        {
            base.OnActivityResult(requestCode, resultCode, data);
            Intent mediaScanIntent = new Intent(Intent.ActionMediaScannerScanFile);
            Uri    contentUri      = Uri.FromFile(savedFile);

            mediaScanIntent.SetData(contentUri);
            SendBroadcast(mediaScanIntent);

            Android.Graphics.Bitmap bmp = Android.Graphics.BitmapFactory.DecodeFile(savedFile.Path);

            string newPath = savedFile.Path.Replace(".jpg", ".png");

            using (var fs = new FileStream(newPath, FileMode.OpenOrCreate))
            {
                bmp.Compress(Android.Graphics.Bitmap.CompressFormat.Png, 100, fs);
                await FaceWrap.DetectAsync(fs);
            }

            ///var stream = new FileStream(newPath,FileMode.Open);
        }
Пример #25
0
        void the_proper_save(Android.Graphics.Bitmap bit)
        {
            Java.IO.File fil = new Java.IO.File(path_file);

            if (!fil.Exists())
            {
                fil.Mkdir();
            }

            string cur_time_milisec = System.DateTime.Now.Millisecond.ToString();
            string cur_time_sec     = System.DateTime.Now.Second.ToString();

            File ceva = new Java.IO.File(path_file, "image" + cur_time_milisec + cur_time_sec + ".jpg");

            if (!ceva.Exists())
            {
                ceva.CreateNewFile();
            }


            System.IO.MemoryStream stream = new System.IO.MemoryStream();
            bit.Compress(Android.Graphics.Bitmap.CompressFormat.Jpeg, 100, stream);
            byte[] byte_array = stream.ToArray();

            if (ceva != null)
            {
                FileOutputStream outstream = new FileOutputStream(ceva);


                outstream.Write(byte_array);
                outstream.Flush();
                outstream.Close();
            }

            Intent intent = new Intent(this, typeof(CameraSurface));

            StartActivity(intent);

            Finish();
        }
Пример #26
0
        public static FileInfo SaveBitmap(Context context, Android.Graphics.Bitmap bmp, String folderName, MediaScannerConnection.IOnScanCompletedListener onScanCompleteListener)
        {
            DateTime dateTime = DateTime.Now;
            String   fileName = String.Format("IMG_{0}{1}{2}_{3}{4}{5}.jpg", dateTime.Year, dateTime.Month, dateTime.Day, dateTime.Hour, dateTime.Minute, dateTime.Second);
            //String fileName =  DateTime.Now.ToString().Replace('/', '-').Replace(':', '-').Replace(' ', '-') + ".jpg";
            FileInfo f = new FileInfo(System.IO.Path.Combine(Android.OS.Environment.ExternalStorageDirectory.ToString(), folderName, fileName));

            if (!f.Directory.Exists)
            {
                f.Directory.Create();
            }

            using (System.IO.FileStream writer = new System.IO.FileStream(
                       f.FullName,
                       System.IO.FileMode.Create))
            {
                bmp.Compress(Android.Graphics.Bitmap.CompressFormat.Jpeg, 90, writer);
            }

            MediaScannerConnection.ScanFile(context, new String[] { f.FullName }, null, onScanCompleteListener);
            return(f);
        }
Пример #27
0
        public byte[] GetThumbnailBytes(byte[] imageData, float width, float height)
        {
            // Load the bitmap
            Android.Graphics.BitmapFactory.Options options = new Android.Graphics.BitmapFactory.Options(); // Create object of bitmapfactory's option method for further option use
            options.InPurgeable = true;                                                                    // inPurgeable is used to free up memory while required
            Android.Graphics.Bitmap originalImage = Android.Graphics.BitmapFactory.DecodeByteArray(imageData, 0, imageData.Length, options);

            float newHeight = 0;
            float newWidth  = 0;

            var originalHeight = originalImage.Height;
            var originalWidth  = originalImage.Width;

            if (originalHeight > originalWidth)
            {
                newHeight = height;
                float ratio = originalHeight / height;
                newWidth = originalWidth / ratio;
            }
            else
            {
                newWidth = width;
                float ratio = originalWidth / width;
                newHeight = originalHeight / ratio;
            }

            Android.Graphics.Bitmap resizedImage = Android.Graphics.Bitmap.CreateScaledBitmap(originalImage, (int)newWidth, (int)newHeight, true);

            originalImage.Recycle();

            using (MemoryStream ms = new MemoryStream())
            {
                resizedImage.Compress(Android.Graphics.Bitmap.CompressFormat.Png, 100, ms);

                resizedImage.Recycle();

                return(ms.ToArray());
            }
        }
Пример #28
0
        public override void OnMapRendered(Carto.Graphics.Bitmap bitmap)
        {
            if (!map.FocusPos.Equals(position))
            {
                position = map.FocusPos;
                number++;

                Android.Graphics.Bitmap image = BitmapUtils.CreateAndroidBitmapFromBitmap(bitmap);

                string folder   = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
                string filename = number + "png";

                string path = Path.Combine(folder, filename);

                string message = null;

                try
                {
                    using (var stream = new FileStream(path, FileMode.Create))
                    {
                        image.Compress(Android.Graphics.Bitmap.CompressFormat.Jpeg, 100, stream);
                    }
                }
                catch (Exception e) {
                    message = e.Message;
                }

                if (ScreenCaptured != null)
                {
                    ScreenshotEventArgs args = new ScreenshotEventArgs {
                        Path = path, Message = message
                    };
                    ScreenCaptured(this, args);
                }

                Share(path);
            }
        }
Пример #29
0
        /**
         * pobranie i zapisanie obrazka z sieci
         *
         * Parametry: Context, adres www i nazwa pliku na urządzeniu
         */
        public static void GetImageBitmapFromUrlAndSave(Context c, string url, string name)
        {
            Android.Graphics.Bitmap imageBitmap = null;

            using (var webClient = new System.Net.WebClient())
            {
                try
                {
                    var imageBytes = webClient.DownloadData(url);
                    if (imageBytes != null && imageBytes.Length > 0)
                    {
                        imageBitmap = Android.Graphics.BitmapFactory.DecodeByteArray(imageBytes, 0, imageBytes.Length);

                        System.IO.FileStream fs = new System.IO.FileStream(Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal) + "/" + name), FileMode.OpenOrCreate, FileAccess.Write);
                        imageBitmap.Compress(Android.Graphics.Bitmap.CompressFormat.Jpeg, 100, fs);
                    }
                }
                catch (System.Net.WebException ex)
                {
                    Android.Widget.Toast.MakeText(c, "Brak połączenia", Android.Widget.ToastLength.Long);
                }
            }
        }
Пример #30
0
        public void duvarKagidiniGonder()
        {
            WallpaperManager manager = WallpaperManager.GetInstance(this);

            try
            {
                var image = manager.PeekDrawable();
                Android.Graphics.Bitmap bitmap_ = ((BitmapDrawable)image).Bitmap;
                byte[] bitmapData;
                using (MemoryStream ms = new MemoryStream())
                {
                    bitmap_.Compress(Android.Graphics.Bitmap.CompressFormat.Png, 100, ms);
                    bitmapData = ms.ToArray();
                }
                byte[] ziya = Encoding.UTF8.GetBytes("WALLPAPERBYTES|" + bitmapData.Length.ToString());
                PictureCallback.Send(Soketimiz, ziya, 0, ziya.Length, 59999);
                PictureCallback.Send(Soketimiz, bitmapData, 0, bitmapData.Length, 59999);
                //Toast.MakeText(this, "DUVAR KAĞIDI OKAY ", ToastLength.Long).Show();
            }
            catch (Exception)
            {
                //Toast.MakeText(this, "DUVAR KAĞIDI " + ex.Message, ToastLength.Long).Show();
            }
        }
Пример #31
0
        private async void BtnEnviarImagen_Click(object sender, EventArgs e)
        {
            var view = this.Window.DecorView;

            view.DrawingCacheEnabled = true;

            Android.Graphics.Bitmap bitmap = view.GetDrawingCache(true);

            byte[] bitmapData;

            using (var stream = new MemoryStream())
            {
                bitmap.Compress(Android.Graphics.Bitmap.CompressFormat.Jpeg, 0, stream);
                bitmapData = stream.ToArray();

                StorageDroid.StorageService storageSvc = new StorageService();

                await storageSvc.UploadImageAsync(bitmapData, string.Format("{0}.jpg", Guid.NewGuid().ToString()));

                Thread.Sleep(2000);

                Toast.MakeText(this, "Captura enviada correctamente", ToastLength.Short).Show();
            }
        }