Xamarin Forms - Resize Camera Picture

前端 未结 4 643
攒了一身酷
攒了一身酷 2020-12-03 09:22

Someone helped me get this code for taking a picture using xamarin forms labs camera:

picker = DependencyService.Get ();  
                       


        
4条回答
  •  既然无缘
    2020-12-03 09:41

    @Sten's answer might encounter out-of-memory problem on some android devices. Here's my solution to implement the ResizeImage function , which is according to google's "Loading Large Bitmaps Efficiently" document:

    public void ResizeImage (string sourceFile, string targetFile, int reqWidth, int reqHeight)
    { 
        if (!File.Exists (targetFile) && File.Exists (sourceFile)) {   
            var downImg = decodeSampledBitmapFromFile (sourceFile, reqWidth, reqHeight);
            using (var outStream = File.Create (targetFile)) {
                if (targetFile.ToLower ().EndsWith ("png"))
                    downImg.Compress (Bitmap.CompressFormat.Png, 100, outStream);
                else
                    downImg.Compress (Bitmap.CompressFormat.Jpeg, 95, outStream);
            }
            downImg.Recycle();
        }
    }
    
    public static Bitmap decodeSampledBitmapFromFile (string path, int reqWidth, int reqHeight)
    {
        // First decode with inJustDecodeBounds=true to check dimensions
        var options = new BitmapFactory.Options ();
        options.InJustDecodeBounds = true;
        BitmapFactory.DecodeFile (path, options);
    
        // Calculate inSampleSize
        options.InSampleSize = calculateInSampleSize (options, reqWidth, reqHeight);
    
        // Decode bitmap with inSampleSize set
        options.InJustDecodeBounds = false;
        return BitmapFactory.DecodeFile (path, options);
    }
    
    public static int calculateInSampleSize (BitmapFactory.Options options, int reqWidth, int reqHeight)
    {
        // Raw height and width of image
        int height = options.OutHeight;
        int width = options.OutWidth;
        int inSampleSize = 1;
    
        if (height > reqHeight || width > reqWidth) {
            int halfHeight = height / 2;
            int halfWidth = width / 2;
    
            // Calculate the largest inSampleSize value that is a power of 2 and keeps both
            // height and width larger than the requested height and width.
            while ((halfHeight / inSampleSize) > reqHeight
                   && (halfWidth / inSampleSize) > reqWidth) {
                inSampleSize *= 2;
            }
        }
    
        return inSampleSize;
    }
    

提交回复
热议问题