在Xamarin.Android中压缩图像字节

时间:2019-05-26 06:37:39

标签: android xamarin xamarin.android

如何使用CameraSourcePreview压缩在Xamarin.Android中拍摄的图像,方法OnPictureTaken中的字节太大。

1 个答案:

答案 0 :(得分:0)

这里是将位图转换为压缩的JPG文件的一种方法。同样在此示例中,还介绍了如何将压缩的JPG文件保存到图片库,并使其通过Android Media Scan通过USB / Windows立即可用。希望这会有所帮助!

    public void OnPictureTaken(byte[] data, Camera camera) {
        var bmp = BitmapFactory.DecodeByteArray(data, 0, data.Length);
        SaveBitmapAsJPEG(bmp, 75);
    }

    public void SaveBitmapAsJPEG(Bitmap pBitmap, int pnQuality = 85) {

        Java.IO.File jFolder = GetCreatePhotoAlbumStorageDir("MyPhotoAlbum");
        Java.IO.File jFile = new Java.IO.File(jFolder, $"Photo_{DateTime.Now.ToString("yyyyMMddHHmmss")}.jpg");

        // "/storage/emulated/0/Pictures/MyPhotoAlbum/Photo_20190526112410.jpg", which is the following via Windows/USB...
        // "Internal shared storage\Pictures\MyPhotoAlbum\Photo_20190526112410.jpg"

        using (var fs = new FileStream(jFile.AbsolutePath, FileMode.CreateNew)) {
            pBitmap.Compress(Bitmap.CompressFormat.Jpeg, pnQuality, fs);
        }

        SavePictureToGallery(jFile);

        Android.Util.Log.Info("MyApp", $"Picture saved using SaveBitmapAsJPEG() at {jFile.AbsolutePath}");

        // Request the media scanner to scan a file and add it to the media database (Make file visible/available through USB connection in Windows Explorer)
        var f = new Java.IO.File(jFile.AbsolutePath);
        var intent = new Intent(Intent.ActionMediaScannerScanFile);
        intent.SetData(Android.Net.Uri.FromFile(f));
        Application.Context.SendBroadcast(intent);
    }

    public Java.IO.File GetCreatePhotoAlbumStorageDir(string psAlbumName) {
        // Get the directory for the user's public pictures directory.  Will create if it doesn't exist.
        var dir = new Java.IO.File(Environment.GetExternalStoragePublicDirectory(Environment.DirectoryPictures), psAlbumName);
        if (!dir.Exists())
            dir.Mkdirs();
        return dir;
    }

    private void SavePictureToGallery(Java.IO.File pFile) {
        var intent = new Intent(MediaStore.ActionImageCapture);
        intent.PutExtra(MediaStore.ExtraOutput, Android.Net.Uri.FromFile(pFile));
        StartActivityForResult(intent, 0);
    }

请注意,您可以根据需要通过将“ CompressFormat”更改为.Png并相应地命名文件来将格式更改为PNG。