目前win8 的SDK中还没有图片压缩处理的API,只能借助第三方的类库来处理。可惜专门针对win8的图片压缩处理的第三方类库也没有。不过还好,win8的API跟Silverlight的API是差不多的,所以可以直接从Silverlight中移植过来。
我找了一个LibJpeg.net的Silverlight版的类库源码,经过简单的修改,改为win8版的图片压缩处理类库。这个类库可以对图片进行按质量百分比的压缩。
下面贴出部分代码。
protected override async void OnNavigatedTo(NavigationEventArgs e) { string str = "http://gimg.vancl.com/img/02/8705542.jpg"; var storageFile = await Windows.Storage.StorageFile.CreateStreamedFileFromUriAsync("temp.jpg", new Uri(str, UriKind.Absolute), null); var file = await storageFile.OpenAsync(Windows.Storage.FileAccessMode.Read); //原图 BitmapImage bitImage1 = new BitmapImage(); bitImage1.SetSource(file); img.Source = bitImage1; txt.Text = "原图大小:" + file.Size; //原图压缩处理 var jpegimage = new JpegImage(file.AsStream()); System.IO.MemoryStream stream = new MemoryStream(); jpegimage.WriteJpeg(stream, new CompressionParameters() { Quality = 20 });//压缩质量为20% byte[] buffer = new byte[stream.Length]; stream.Seek(0, SeekOrigin.Begin); stream.Read(buffer, 0, buffer.Length); var ibuffer = CryptographicBuffer.CreateFromByteArray(buffer); InMemoryRandomAccessStream memoryRandomStream = new InMemoryRandomAccessStream(); await memoryRandomStream.WriteAsync(ibuffer); memoryRandomStream.Seek(0); BitmapImage bitImage2 = new BitmapImage(); bitImage2.SetSource(memoryRandomStream); img2.Source = bitImage2; txt2.Text = "压缩后图片大小:" + memoryRandomStream.Size; }