C#如何减小流的大小(图像)

时间:2017-06-20 09:57:14

标签: c# android image

我所拥有的只是文件的Stream(文件为image/jpeg类型)。我想降低图像的质量(例如:原始2MB - > 200KB)。

var contentStream = ImageSource.FromStream(() => { return _MediaFile.GetStream(); });

newImg.Source = contentStream;

_ReportModel.Add(new ReportPicture()
{
    Id = layout.Id,
    Path = _MediaFile.Path,
    Content = _MediaFile.GetStream()
});

在使用REST API将_ReportModel上传到我的服务器之前,我希望减少包含读取图像流的Content的大小(类型为jpeg)。

我需要类似的东西:

private Stream ReduceStreamSize(Stream oldStream)
{
    var reducedStream = //doSomething(oldStream);
    return reducedStream;
}

我该怎么做?

更新

我试过这个:

public Stream CompressImage(string imagePath)
    {
        try
        {

            // BitmapFactory options to downsize the image
            BitmapFactory.Options o = new BitmapFactory.Options();
            o.InJustDecodeBounds = true;
            o.InSampleSize = 6;
            // factor of downsizing the image

            FileStream inputStream = new FileStream(imagePath, FileMode.Open);
            //Bitmap selectedBitmap = null;
            BitmapFactory.DecodeStream(inputStream, null, o);
            inputStream.Close();

            // The new size we want to scale to
            int REQUIRED_SIZE = 75;

            // Find the correct scale value. It should be the power of 2.
            int scale = 1;
            while (o.OutWidth / scale / 2 >= REQUIRED_SIZE &&
                            o.OutHeight / scale / 2 >= REQUIRED_SIZE)
            {
                scale *= 2;
            }

            BitmapFactory.Options o2 = new BitmapFactory.Options();
            o2.InSampleSize = scale;
            inputStream = new FileStream(imagePath, FileMode.Open);

            Bitmap selectedBitmap = BitmapFactory.DecodeStream(inputStream, null, o2);
            inputStream.Close();

            FileStream outputStream = new FileStream(imagePath, FileMode.Open);

            selectedBitmap.Compress(Bitmap.CompressFormat.Jpeg, 100, outputStream);

            return outputStream;
        }
        catch (Exception e)
        {
            return null;
        }
    }

但图像没有显示。压缩时必定会出错。

0 个答案:

没有答案