Beispiel #1
0
        public static AMatrix ToAndroid(this Transform transform, float density = 1)
        {
            AMatrix aMatrix = new AMatrix();

            if (transform == null)
            {
                return(aMatrix);
            }

            Matrix matrix = transform.Value;

            aMatrix.SetValues(
                new float[] {
                (float)matrix.M11,
                (float)matrix.M21,
                (float)matrix.OffsetX * density,
                (float)matrix.M12,
                (float)matrix.M22,
                (float)matrix.OffsetY * density,
                0,
                0,
                1
            });

            return(aMatrix);
        }
Beispiel #2
0
        public static Android.Graphics.Bitmap Rotate(Android.Graphics.Bitmap bitmap, int angle)
        {
            var mat = new Android.Graphics.Matrix();

            mat.PostRotate(angle);
            return(Android.Graphics.Bitmap.CreateBitmap(bitmap, 0, 0, bitmap.Width, bitmap.Height, mat, true));
        }
        /// <summary>
        /// Rotate the picture taken
        /// https://forums.xamarin.com/discussion/5409/photo-being-saved-in-landscape-not-portrait
        /// </summary>
        /// <param name="path"></param>
        /// <param name="width"></param>
        /// <param name="height"></param>
        /// <returns></returns>
        void RotateBitmap(string path, byte[] data)
        {
            try
            {
                //using (Android.Graphics.Bitmap picture = Android.Graphics.BitmapFactory.DecodeFile(path))
                using (Android.Graphics.Bitmap picture = data.ToBitmap())
                    using (Android.Graphics.Matrix mtx = new Android.Graphics.Matrix())
                    {
                        ExifInterface exif           = new ExifInterface(path);
                        string        orientation    = exif.GetAttribute(ExifInterface.TagOrientation);
                        var           camOrientation = int.Parse(orientation);

                        switch (_imageRotation)
                        {
                        case 0: // landscape
                            break;

                        case 90: // landscape upside down
                            mtx.PreRotate(270);
                            break;

                        case 180: // portrait
                            mtx.PreRotate(180);
                            break;

                        case 270: // portrait upside down
                            mtx.PreRotate(90);
                            break;
                        }

                        var    maxSize = 1024;
                        double w       = picture.Width;
                        double h       = picture.Height;
                        if (picture.Width > maxSize || picture.Height > maxSize)
                        {
                            // set scaled width and height to prevent out of memory exception
                            double scaleFactor = (double)maxSize / (double)picture.Width;
                            if (picture.Height > picture.Width)
                            {
                                scaleFactor = (double)maxSize / picture.Height;
                            }

                            w = picture.Width * scaleFactor;
                            h = picture.Height * scaleFactor;
                        }

                        using (var scaledPiture = Android.Graphics.Bitmap.CreateScaledBitmap(picture, (int)w, (int)h, false))
                            using (var rotatedPiture = Android.Graphics.Bitmap.CreateBitmap(scaledPiture, 0, 0, (int)w, (int)h, mtx, false))
                            {
                                SaveFile(path, rotatedPiture.ToBytes());
                            }
                    }
            }
            catch (Java.Lang.OutOfMemoryError e)
            {
                e.PrintStackTrace();
                throw;
            }
        }
 public Android.Graphics.Bitmap rotateMyBitmap(Android.Graphics.Bitmap bmp)
 {
     //*****旋转一下
     Android.Graphics.Matrix matrix = new Android.Graphics.Matrix();
     matrix.PostRotate(270);
     Android.Graphics.Bitmap nbmp2 = Android.Graphics.Bitmap.CreateBitmap(bmp, 0, 0, bmp.Width, bmp.Height, matrix, true);
     bmp.Dispose();
     return(nbmp2);
 }
Beispiel #5
0
        public static Android.Graphics.Bitmap rotateBitmap(Android.Graphics.Bitmap bitmap, int orientation)
        {
            Android.Graphics.Matrix matrix = new Android.Graphics.Matrix();
            switch (orientation)
            {
            case (int)Android.Media.Orientation.Normal:
                return(bitmap);

            case (int)Android.Media.Orientation.FlipHorizontal:
                matrix.SetScale(-1, 1);
                break;

            case (int)Android.Media.Orientation.Rotate180:
                matrix.SetRotate(180);
                break;

            case (int)Android.Media.Orientation.FlipVertical:
                matrix.SetRotate(180);
                matrix.PostScale(-1, 1);
                break;

            case (int)Android.Media.Orientation.Transpose:
                matrix.SetRotate(90);
                matrix.PostScale(-1, 1);
                break;

            case (int)Android.Media.Orientation.Rotate90:
                matrix.SetRotate(90);
                break;

            case (int)Android.Media.Orientation.Transverse:
                matrix.SetRotate(-90);
                matrix.PostScale(-1, 1);
                break;

            case (int)Android.Media.Orientation.Rotate270:
                matrix.SetRotate(-90);
                break;

            default:
                return(bitmap);
            }
            try
            {
                Android.Graphics.Bitmap bmRotated = Android.Graphics.Bitmap.CreateBitmap(bitmap, 0, 0, bitmap.Width, bitmap.Height, matrix, true);
                bitmap.Recycle();
                return(bmRotated);
            }
            catch (Java.Lang.OutOfMemoryError e)
            {
                e.PrintStackTrace();
                return(null);
            }
        }
        private static Android.Graphics.Bitmap RotateImage(string filePath, int rotation)
        {
            var originalImage = Android.Graphics.BitmapFactory.DecodeFile(filePath);

            var matrix = new Android.Graphics.Matrix();

            matrix.PostRotate(rotation);
            var rotatedImage = Android.Graphics.Bitmap.CreateBitmap(originalImage, 0, 0, originalImage.Width, originalImage.Height, matrix, true);

            originalImage.Recycle();
            return(rotatedImage);
        }
Beispiel #7
0
        public static Android.Graphics.Matrix ToNative(this Matrix3x2 matrix)
        {
            var nativeMatrix = new Android.Graphics.Matrix();

            nativeMatrix.SetValues(new[]
            {
                matrix.M11, matrix.M21, matrix.M31,
                matrix.M12, matrix.M22, matrix.M32,
                0, 0, 1
            });
            return(nativeMatrix);
        }
Beispiel #8
0
        public void OnPictureTaken(byte[] data, Camera camera)
        {
            camera.StartPreview();
            Task.Run(() => {
                try
                {
                    var fileService = DependencyService.Get <IFileService>();

                    var fileName = "photo_" + DateTime.Now.ToString() + ".jpg";
                    fileName     = fileName.Replace("/", "_");

                    fileName = System.IO.Path.Combine(fileService.AppWorkPath, fileName);

                    //                   File.WriteAllBytes(fileName, data);

                    var rotate = 90;
                    if (rotate > 0)
                    {
                        var matrix = new Android.Graphics.Matrix();
                        matrix.PostRotate(rotate);

                        var bitmap        = Android.Graphics.BitmapFactory.DecodeByteArray(data, 0, data.Length); // MediaStore.Images.Media.GetBitmap(this.ContentResolver, Android.Net.Uri.Parse(uri));
                        var rotatedBitmap = Android.Graphics.Bitmap.CreateBitmap(bitmap, 0, 0, bitmap.Width, bitmap.Height, matrix, true);
                        bitmap.Recycle();
                        bitmap = rotatedBitmap;

                        using (var finalStream = new MemoryStream())
                        {
                            bitmap.Compress(Android.Graphics.Bitmap.CompressFormat.Jpeg, 100, finalStream);
                            data = finalStream.GetBuffer();
                        }

                        File.WriteAllBytes(fileName, data);

                        bitmap.Recycle();
                        GC.Collect();
                    }

                    if (this.CameraPreviewCallback != null)
                    {
                        this.CameraPreviewCallback.AfterPictureTaken(fileName);
                    }
                }
                catch
                {
                }
            });
        }
Beispiel #9
0
        /// <summary>
        /// Read the file into a Mat
        /// </summary>
        /// <param name="fileName">The file to read from</param>
        /// <param name="mat">The Mat to read the file into</param>
        /// <param name="loadType">The load type</param>
        /// <returns>True if successfully read file into Mat</returns>
        public bool ReadFile(String fileName, Mat mat, CvEnum.ImreadModes loadType)
        {
            try
            {
                int rotation = 0;
                Android.Media.ExifInterface exif = new Android.Media.ExifInterface(fileName);
                int orientation = exif.GetAttributeInt(Android.Media.ExifInterface.TagOrientation, int.MinValue);
                switch (orientation)
                {
                case (int)Android.Media.Orientation.Rotate270:
                    rotation = 270;
                    break;

                case (int)Android.Media.Orientation.Rotate180:
                    rotation = 180;
                    break;

                case (int)Android.Media.Orientation.Rotate90:
                    rotation = 90;
                    break;
                }

                using (Android.Graphics.Bitmap bmp = Android.Graphics.BitmapFactory.DecodeFile(fileName))
                {
                    if (rotation == 0)
                    {
                        bmp.ToMat(mat);
                    }
                    else
                    {
                        Android.Graphics.Matrix matrix = new Android.Graphics.Matrix();
                        matrix.PostRotate(rotation);
                        using (Android.Graphics.Bitmap rotated = Android.Graphics.Bitmap.CreateBitmap(bmp, 0, 0, bmp.Width, bmp.Height, matrix, true))
                        {
                            rotated.ToMat(mat);
                        }
                    }
                }
                return(true);
            }
            catch (Exception e)
            {
                Debug.WriteLine(e);
                //throw;
                return(false);
            }
        }
Beispiel #10
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();
        }
Beispiel #11
0
        internal Android.Graphics.Matrix ToNativeMatrix(Android.Graphics.Matrix targetMatrix = null, Point origin = new Point(), Size size = new Size())
        {
            var matrix = ToMatrix(origin, size);

            if (targetMatrix == null)
            {
                targetMatrix = new Android.Graphics.Matrix();
            }

            targetMatrix.SetValues(new[]
            {
                matrix.M11, matrix.M21, matrix.M31 * (float)size.Width,
                matrix.M12, matrix.M22, matrix.M32 * (float)size.Height,
                0, 0, 1
            });

            return(targetMatrix);
        }
        private void CorrectImageOrientation(string imagePath)
        {
            ExifInterface ei          = new ExifInterface(imagePath);
            int           orientation = ei.GetAttributeInt(ExifInterface.TagOrientation, (int)Orientation.Undefined);

            var  matrix           = new Android.Graphics.Matrix();
            bool rotationIsNeeded = true;

            switch (orientation)
            {
            case (int)Orientation.Rotate90:
                matrix.PostRotate(90);
                break;

            case (int)Orientation.Rotate180:
                matrix.PostRotate(180);
                break;

            case (int)Orientation.Rotate270:
                matrix.PostRotate(270);
                break;

            default:
                rotationIsNeeded = false;
                break;
            }
            if (rotationIsNeeded)
            {
                var sourceBitmap  = Android.Graphics.BitmapFactory.DecodeFile(imagePath);
                var rotatedBitmap = Android.Graphics.Bitmap.CreateBitmap(sourceBitmap, 0, 0, sourceBitmap.Width, sourceBitmap.Height, matrix, true);
                sourceBitmap.Dispose();
                App.FileHelper.DeleteFile(imagePath);
                var outStream = App.FileHelper.CreateFile(imagePath);
                rotatedBitmap.Compress(Android.Graphics.Bitmap.CompressFormat.Jpeg, 100, outStream);
                rotatedBitmap.Dispose();
                outStream.Close();
                outStream.Dispose();
            }
        }
        public async void OnPictureTaken(byte[] data, Android.Hardware.Camera camera)
        {
            using (var bmp = await Android.Graphics.BitmapFactory.DecodeByteArrayAsync(data, 0, data.Length))
            {
                using (var resized = bmp.DefaultResize())
                {
                    var mat = new Android.Graphics.Matrix();

                    var info = new Android.Hardware.Camera.CameraInfo();
                    Android.Hardware.Camera.GetCameraInfo(currentCamera, info);

                    if (info.Facing == CameraFacing.Front)
                    {
                        mat.PostScale(-1, 1);
                    }

                    mat.PostRotate(90);
                    var correctBmp = Android.Graphics.Bitmap.CreateBitmap(resized, 0, 0, resized.Width, resized.Height, mat, true);
                    _captureComplete.SetResult(correctBmp);
                    _captureComplete = null;
                }
            }
        }
Beispiel #14
0
        protected override void Draw(Canvas canvas, Rect bounds)
        {
            int   saveCount = canvas.Save();
            RectF arcBounds = mTempBounds;

            arcBounds.Set(bounds);

            mPaint.Color = new Color(mColor);

            //calculate fish clip bounds
            //clip the width of the fish need to increase mPathDottedLineSize * 1.2f
            RectF  fishRectF = new RectF(mFishHeadPos[0] - mFishWidth / 2.0f - mPathDottedLineSize * 1.2f, mFishHeadPos[1] - mFishHeight / 2.0f, mFishHeadPos[0] + mFishWidth / 2.0f + mPathDottedLineSize * 1.2f, mFishHeadPos[1] + mFishHeight / 2.0f);
            Matrix matrix    = new Matrix();

            matrix.PostRotate(mFishRotateDegrees, fishRectF.CenterX(), fishRectF.CenterY());
            matrix.MapRect(fishRectF);

            //draw river
            int riverSaveCount = canvas.Save();

            mPaint.SetStyle(Paint.Style.Stroke);
            canvas.ClipRect(fishRectF, Region.Op.Difference);
            canvas.DrawPath(CreateRiverPath(arcBounds), mPaint);
            canvas.RestoreToCount(riverSaveCount);

            //draw fish
            int fishSaveCount = canvas.Save();

            mPaint.SetStyle(Paint.Style.Fill);
            canvas.Rotate(mFishRotateDegrees, mFishHeadPos[0], mFishHeadPos[1]);
            canvas.ClipPath(CreateFishEyePath(mFishHeadPos[0], mFishHeadPos[1] - mFishHeight * 0.06f), Region.Op.Difference);
            canvas.DrawPath(CreateFishPath(mFishHeadPos[0], mFishHeadPos[1]), mPaint);
            canvas.RestoreToCount(fishSaveCount);

            canvas.RestoreToCount(saveCount);
        }
 public bool SetDisplayMatrix(Android.Graphics.Matrix finalMatrix)
 {
     return(mAttacher.SetDisplayMatrix(finalMatrix));
 }
Beispiel #16
0
 public void UpdateTransform(AMatrix transform)
 {
     UpdateShapeTransform(transform);
 }
        /// <summary>
        /// Take a picture and perform previews
        /// </summary>
        /// <param name="data"></param>
        /// <param name="camera"></param>
        void Camera.IPictureCallback.OnPictureTaken(byte[] data, Android.Hardware.Camera camera)
        {
			if (data != null && _box != null)
            {
				if (!_processDialog.IsShowing) {
					_processDialog.SetMessage ("Waiting for image results...");
					_processDialog.Show ();
				}
				Android.Graphics.BitmapFactory.Options options = new Android.Graphics.BitmapFactory.Options ();
				options.InJustDecodeBounds = true;
				options.InSampleSize = 2;
				options.InJustDecodeBounds = false;
				options.InTempStorage = new byte[16 * 1024];
                Android.Graphics.Bitmap bmp = Android.Graphics.BitmapFactory.DecodeByteArray(data, 0, data.Length, options);
                data = null;
				GC.Collect ();
                Android.Graphics.Bitmap rotatedBitmap;
                if (bmp.Width > bmp.Height)
                {
                    Android.Graphics.Matrix mtx = new Android.Graphics.Matrix();
                    mtx.SetRotate(90);
                    rotatedBitmap = Android.Graphics.Bitmap.CreateBitmap(bmp, 0, 0, bmp.Width, bmp.Height, mtx, false);
                    bmp.Recycle();
                    mtx.Dispose();
                    mtx = null;
                }
                else
                {
                    rotatedBitmap = bmp.Copy(bmp.GetConfig(), true);
                    bmp.Recycle();
                }
				GC.Collect ();
                double ratioX = (double)rotatedBitmap.Width / (double)screenWidth;
                double ratioY = (double)rotatedBitmap.Height / (double)screenHeight;
                int startX = (int)(ratioX * (double)(_box.MidX - _box.Width / 2));
                int startY = (int)(ratioY * (double)(_box.MidY - _box.Height / 2));
                int width = (int)(ratioX * (double)_box.Width);
                int height = (int)(ratioY * (double)_box.Height);
                Android.Graphics.Bitmap croppedBitmap = Android.Graphics.Bitmap.CreateBitmap(rotatedBitmap, startX, startY, width, height);
                rotatedBitmap.Recycle();
				GC.Collect ();
                bitmap = croppedBitmap.Copy(croppedBitmap.GetConfig(), true);
                PerformPreviews(croppedBitmap);
            }
            else
            {
                Toast.MakeText(this, "Data null error", ToastLength.Long).Show();
            }
        }
Beispiel #18
0
 public bool SetDisplayMatrix(Android.Graphics.Matrix finalMatrix) => _attacher.SetDisplayMatrix(finalMatrix);
Beispiel #19
0
 public static Android.Graphics.Bitmap rotateImage(Android.Graphics.Bitmap source, float angle)
 {
     Android.Graphics.Matrix matrix = new Android.Graphics.Matrix();
     matrix.PostRotate(angle);
     return(Android.Graphics.Bitmap.CreateBitmap(source, 0, 0, source.Width, source.Height, matrix, true));
 }
Beispiel #20
0
 public void ResetTransform()
 {
     Flush();
     using(var m = new Android.Graphics.Matrix())
         ACanvas.Matrix = m;
 }
Beispiel #21
0
            public override void Draw(Android.Graphics.Canvas canvas)
            {
                if (Control == null) return;

                Control.CreateGraphicBuffers();

                if (origMatrix == null)
                {
                    origMatrix = new Android.Graphics.Matrix();
                    origMatrix.Set (canvas.Matrix);
                }
                if (hMatrix == null)
                {
                    hMatrix = new Android.Graphics.Matrix();
                    hMatrix.Set(origMatrix);
                    hMatrix.PostTranslate(-Control.offBmp.Width, 0);
                    hMatrix.PostScale(-1, 1);
                }
                if (vMatrix == null)
                {
                    vMatrix = new Android.Graphics.Matrix();
                    vMatrix.Set(origMatrix);
                    vMatrix.PostTranslate(0, -Control.offBmp.Height);
                    vMatrix.PostScale(1, -1);
                }

                var ctime = System.Environment.TickCount;
                var realupdate = false;
                Fleux.UIElements.Canvas.drawtime = 0;
                /**/
                if (Control.offNeedExtraDraw && Control.offUpdated)
                lock(Control.offBmp){
                    Control.offNeedExtraDraw = false;
                    Control.offUpdated = false;

                    Control.offBmpDraw = true;
                    Control.Draw(new PaintEventArgs(Control.offGr, new Rectangle(0,0, Control.offBmp.Width, Control.offBmp.Height)));
                    Control.offBmpDraw = false;

                    updcnt++;
                    realupdate = true;
                }
                //*/
                lock(Control.offBmp)
                {
                    if (Fleux.Core.FleuxApplication.HorizontalMirror)
                    {
                        canvas.Matrix = hMatrix;
                    }else if (Fleux.Core.FleuxApplication.VerticalMirror)
                    {
                        canvas.Matrix = vMatrix;
                    }else
                        canvas.Matrix = origMatrix;

                    // Thats for FastGraphics.cs
                    Control.offGr.Flush();

                    canvas.DrawBitmap(Control.offBmp.ABitmap, 0,0, paint);
                    Control.offUpdated = false;
                    updcntflush++;
                }
                if (PerfData)
                {
                    ctime = System.Environment.TickCount - ctime;
                    //if (realupdate)
                    {
                        totime += ctime;
                    }
                    var cavg = totime / (updcnt+1);

                    var cpaint = new Android.Graphics.Paint();
                    cpaint.Color = new Android.Graphics.Color(0xA0, 0xFF, 0xFF, 0xFF);
                    cpaint.SetStyle(Android.Graphics.Paint.Style.Fill);
                    canvas.DrawRect(0,0, 250, 20, cpaint);
                    canvas.DrawText(""+updcnt+":"+updcntflush+":"+updcntinval+" ctime: "+ctime+"cavg:"+cavg+" canv: "+Fleux.UIElements.Canvas.drawtime, 0,20, spaint);
                    cpaint.Dispose();
                    if (updcnt > 100)
                    {
                        totime = 0;
                        updcnt = 0;
                    }
                }
            }
        private static Android.Graphics.Bitmap RotateImage(string filePath, int rotation)
        {
            var originalImage = Android.Graphics.BitmapFactory.DecodeFile(filePath);

            var matrix = new Android.Graphics.Matrix();
            matrix.PostRotate(rotation);
            var rotatedImage = Android.Graphics.Bitmap.CreateBitmap(originalImage, 0, 0, originalImage.Width, originalImage.Height, matrix, true);
            originalImage.Recycle();
            return rotatedImage;
        }
        private Android.Graphics.Bitmap LoadAndResizeBitmap(string fileName, Size newSize) {
            var exif = new ExifInterface(fileName);

            var width = exif.GetAttributeInt(ExifInterface.TagImageWidth, 100);
            var height = exif.GetAttributeInt(ExifInterface.TagImageLength, 80);
            var orientation = exif.GetAttribute(ExifInterface.TagOrientation);


            // We calculate the ratio that we need to resize the image by
            // in order to fit the requested dimensions.

            var inSampleSize = 1.0;

            if (newSize.Height < height || newSize.Width < width) {
                inSampleSize = newSize.Width > newSize.Height
                    ? newSize.Height / height
                        : newSize.Width / width;
            }

            var options = new Android.Graphics.BitmapFactory.Options {
                InJustDecodeBounds = false,
                InSampleSize = (int)inSampleSize
            };
            // Now we will load the image and have BitmapFactory resize it for us.
            var resizedBitmap = Android.Graphics.BitmapFactory.DecodeFile(fileName, options);

            var rotate = false;
            
            switch (orientation) {
                case "1": // landscape
                case "3": // landscape
                    if (width < height)
                        rotate = true;
                    break;
                case "8":
                case "4":
                case "6": // portrait
                    if (width > height)
                        rotate = true;
                    break;
                case "0": //undefined
                default:
                    break;
            }

            if (rotate) {
                var mtx = new Android.Graphics.Matrix();
                mtx.PreRotate(90);
                resizedBitmap = Android.Graphics.Bitmap.CreateBitmap(resizedBitmap, 0, 0, resizedBitmap.Width, resizedBitmap.Height, mtx, false);
                mtx.Dispose();
                mtx = null;

            }


            return resizedBitmap;
        }
        private Android.Graphics.Bitmap LoadAndResizeBitmap(string fileName, Size newSize)
        {
            var exif = new ExifInterface(fileName);

            var width       = exif.GetAttributeInt(ExifInterface.TagImageWidth, 100);
            var height      = exif.GetAttributeInt(ExifInterface.TagImageLength, 80);
            var orientation = exif.GetAttribute(ExifInterface.TagOrientation);


            // We calculate the ratio that we need to resize the image by
            // in order to fit the requested dimensions.

            var inSampleSize = 1.0;

            if (newSize.Height < height || newSize.Width < width)
            {
                inSampleSize = newSize.Width > newSize.Height
                    ? newSize.Height / height
                        : newSize.Width / width;
            }

            var options = new Android.Graphics.BitmapFactory.Options {
                InJustDecodeBounds = false,
                InSampleSize       = (int)inSampleSize
            };
            // Now we will load the image and have BitmapFactory resize it for us.
            var resizedBitmap = Android.Graphics.BitmapFactory.DecodeFile(fileName, options);

            var rotate = false;

            switch (orientation)
            {
            case "1":     // landscape
            case "3":     // landscape
                if (width < height)
                {
                    rotate = true;
                }
                break;

            case "8":
            case "4":
            case "6":     // portrait
                if (width > height)
                {
                    rotate = true;
                }
                break;

            case "0":     //undefined
            default:
                break;
            }

            if (rotate)
            {
                var mtx = new Android.Graphics.Matrix();
                mtx.PreRotate(90);
                resizedBitmap = Android.Graphics.Bitmap.CreateBitmap(resizedBitmap, 0, 0, resizedBitmap.Width, resizedBitmap.Height, mtx, false);
                mtx.Dispose();
                mtx = null;
            }


            return(resizedBitmap);
        }
Beispiel #25
0
        /// <summary>
        /// Write picture data to stream. The picture will be rotated if necessary.
        /// </summary>
        public async Task WriteDataToStream(byte[] data, Stream writeStream)
        {
            var rotate = _displayOrientation;

            if (rotate == 0)
            {
                using (var ms = new MemoryStream(data))
                {
                    await ms.CopyToAsync(writeStream);
                }
            }
            else
            {
                using (var sourceBm = await Android.Graphics.BitmapFactory.DecodeByteArrayAsync(data, 0, data.Length))
                {
                    using (var m = new Android.Graphics.Matrix())
                    {
                        m.PostRotate(rotate);
                        using (var bm = Android.Graphics.Bitmap.CreateBitmap(sourceBm, 0, 0, sourceBm.Width, sourceBm.Height, m, true))
                        {
                            if (sourceBm != bm) { sourceBm.Recycle(); }
                            await bm.CompressAsync(Android.Graphics.Bitmap.CompressFormat.Jpeg, 100, writeStream);
                            bm.Recycle();
                        }
                    }
                }
            }
        }
        /// <summary>
        /// Rotate via EXIF information
        /// </summary>
        /// <param name="photoPath"></param>
        /// <returns></returns>
        public byte[] RotateImage(string photoPath)
        {
            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);

            try
            {
                Android.Media.ExifInterface exifInterface = new Android.Media.ExifInterface(photoPath);
                int orientation = exifInterface.GetAttributeInt(Android.Media.ExifInterface.TagOrientation, (int)Android.Media.Orientation.Normal);

                int rotate = 0;

                switch (orientation)
                {
                case (int)Android.Media.Orientation.Normal:
                    rotate = 0;
                    break;

                case (int)Android.Media.Orientation.Rotate90:
                    rotate = 90;
                    break;

                case (int)Android.Media.Orientation.Rotate270:
                    rotate = 270;
                    break;

                case (int)Android.Media.Orientation.Rotate180:
                    rotate = 180;
                    break;

                default:
                    rotate = 0;
                    break;
                }

                using (var ms = new System.IO.MemoryStream())
                {
                    Android.Graphics.Bitmap croppedBitmap = null;

                    Android.Graphics.Matrix mtx = new Android.Graphics.Matrix();
                    mtx.PreRotate(rotate);

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

                    croppedBitmap.Compress(Android.Graphics.Bitmap.CompressFormat.Png, 100, ms);

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

                    mtx.Dispose();
                    mtx = null;

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

                    return(ms.ToArray());
                }
            }
            catch
            {
                // <!-- Fail out -->
            }

            return(null);
        }
Beispiel #27
0
            public override void OnResourceReady(Java.Lang.Object p0, Com.Bumptech.Glide.Request.Transition.ITransition p1)
            {
                float density    = currentContext.Resources.DisplayMetrics.Density;
                float MIN_WIDTH  = 60 * density;
                float MAX_WIDTH  = 200 * density;
                float MIN_HEIGHT = 60 * density;
                float MAX_HEIGHT = 200 * density;

                var resource    = p0 as Android.Graphics.Bitmap;
                int imageWidth  = resource.Width;
                int imageHeight = resource.Height;

                // 裁剪 bitmap
                float width, height;

                if (imageWidth > imageHeight)
                {
                    if (imageWidth > MAX_WIDTH)
                    {
                        float temp = MAX_WIDTH / imageWidth * imageHeight;
                        height = temp > MIN_HEIGHT ? temp : MIN_HEIGHT;
                        width  = MAX_WIDTH;
                    }
                    else if (imageWidth < MIN_WIDTH)
                    {
                        float temp = MIN_WIDTH / imageWidth * imageHeight;
                        height = temp < MAX_HEIGHT ? temp : MAX_HEIGHT;
                        width  = MIN_WIDTH;
                    }
                    else
                    {
                        float ratio = imageWidth / imageHeight;
                        if (ratio > 3)
                        {
                            ratio = 3;
                        }
                        height = imageHeight * ratio;
                        width  = imageWidth;
                    }
                }
                else
                {
                    if (imageHeight > MAX_HEIGHT)
                    {
                        float temp = MAX_HEIGHT / imageHeight * imageWidth;
                        width  = temp > MIN_WIDTH ? temp : MIN_WIDTH;
                        height = MAX_HEIGHT;
                    }
                    else if (imageHeight < MIN_HEIGHT)
                    {
                        float temp = MIN_HEIGHT / imageHeight * imageWidth;
                        width  = temp < MAX_WIDTH ? temp : MAX_WIDTH;
                        height = MIN_HEIGHT;
                    }
                    else
                    {
                        float ratio = imageHeight / imageWidth;
                        if (ratio > 3)
                        {
                            ratio = 3;
                        }
                        width  = imageWidth * ratio;
                        height = imageHeight;
                    }
                }

                var layoutParms = imageView.LayoutParameters;

                layoutParms.Width          = (int)width;
                layoutParms.Height         = (int)height;
                imageView.LayoutParameters = layoutParms;
                var   matrix      = new Android.Graphics.Matrix();
                float scaleWidth  = width / imageWidth;
                float scaleHeight = height / imageHeight;

                matrix.PostScale(scaleWidth, scaleHeight);
                imageView.SetImageBitmap(Android.Graphics.Bitmap.CreateBitmap(resource, 0, 0, imageWidth, imageHeight, matrix, true));
            }
Beispiel #28
0
 public void ResetTransform()
 {
     using (var m = new Android.Graphics.Matrix())
         ACanvas.Matrix = m;
 }
Beispiel #29
0
 internal virtual Android.Graphics.Matrix ToNative(Android.Graphics.Matrix targetMatrix = null, Size size = new Size(), bool isBrush = false)
 {
     throw new NotImplementedException();
 }