2015-10-01 69 views
0

我有这样一段代码由web服务检索图像,并将其保存到StorageFile调整大小图像 - 视窗8

StorageFolder folder = await ApplicationData.Current.LocalFolder.CreateFolderAsync(Constants.DataDirectory, CreationCollisionOption.OpenIfExists); 
StorageFile imgFile; 

using (var httpClient = new HttpClient { BaseAddress = Constants.baseAddress }) 
{ 
    string token = App.Current.Resources["token"] as string; 
    httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); 

    using (var response2 = await httpClient.GetAsync("user/image?userId=" + id)) 
    { 
     Stream imageStream = await response2.Content.ReadAsStreamAsync(); 
     if (imageStream.Length != 0) 
     { 
      byte[] bytes = new byte[imageStream.Length]; 
      imageStream.Read(bytes, 0, (int)imageStream.Length); 
      imgFile = await folder.CreateFileAsync(fname, CreationCollisionOption.ReplaceExisting); 
      await FileIO.WriteBytesAsync(imgFile, bytes); //i want the image bytes to be of a smaller version of the image at this point 
     } 
     return await response2.Content.ReadAsStringAsync(); 
    } 
} 

我会想知道是否有方法将图像bytes[]转换为缩略图版本(例如50x50),然后将它们写入StorageFile

+0

查看我在这里提供的解决方案:http://stackoverflow.com/questions/32792626/reduce-image-size-physical-and-dimensions-coming-from-httppostedfilebase-then – Lorek

回答

1

这里来调整图像流的代码:

   var decoder = await BitmapDecoder.CreateAsync(stream); 

       var pixels = await decoder.GetPixelDataAsync(); 

       var file = await folder.CreateFileAsync($"{_oriFile.DisplayName}_{size}.png",CreationCollisionOption.GenerateUniqueName); 
       using (var fileStream = await file.OpenAsync(FileAccessMode.ReadWrite)) 
       { 

        var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, fileStream); 

        encoder.BitmapTransform.ScaledWidth = size; 
        encoder.BitmapTransform.ScaledHeight = size; 

        encoder.SetPixelData(
         decoder.BitmapPixelFormat, 
         decoder.BitmapAlphaMode, 
         decoder.PixelWidth, decoder.PixelHeight, 
         decoder.DpiX, decoder.DpiY, 
         pixels.DetachPixelData()); 

        encoder.BitmapTransform.InterpolationMode = BitmapInterpolationMode.Fant; 

        await encoder.FlushAsync(); 
       } 

当你得到的图像流,你应该做的事情调整大小将其保存为StorageFile之前。当然,您可以在将其保存到StorageFile后进行此操作。