using System;
using System.Threading.Tasks;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Graphics.Imaging;
using Windows.UI.Xaml.Media.Imaging;
using Windows.Storage;
using Windows.Storage.Pickers;
using Windows.Storage.Streams;
using System.IO;
using Windows.Foundation;
using System.Collections.Generic; namespace Common
{
public class ImageHelper
{
public const int THumbLength = ;
public static Size MinSizeSupported = new Size(, );
public static Size MaxSizeSupported = new Size(, ); static Guid EncoderIDFromFileExtension(string strExtension)
{
Guid encoderId;
switch (strExtension.ToLower())
{
case ".jpg":
case ".jpeg":
encoderId = BitmapEncoder.JpegEncoderId;
break;
case ".bmp":
encoderId = BitmapEncoder.BmpEncoderId;
break;
case ".png":
default:
encoderId = BitmapEncoder.PngEncoderId;
break;
}
return encoderId;
}
static Guid DecoderIDFromFileExtension(string strExtension)
{
Guid encoderId;
switch (strExtension.ToLower())
{
case ".jpg":
case ".jpeg":
encoderId = BitmapDecoder.JpegDecoderId;
break;
case ".bmp":
encoderId = BitmapDecoder.BmpDecoderId;
break;
case ".png":
default:
encoderId = BitmapDecoder.PngDecoderId;
break;
}
return encoderId;
} public async static Task<WriteableBitmap> ReadBitmap(IRandomAccessStream fileStream, string type)
{
WriteableBitmap bitmap = null;
try
{
Guid decoderId = DecoderIDFromFileExtension(type); BitmapDecoder decoder = await BitmapDecoder.CreateAsync(decoderId, fileStream);
BitmapTransform tf = new BitmapTransform(); uint width = decoder.OrientedPixelWidth;
uint height = decoder.OrientedPixelHeight;
double dScale = ; if (decoder.OrientedPixelWidth > MaxSizeSupported.Width || decoder.OrientedPixelHeight > MaxSizeSupported.Height)
{
dScale = Math.Min(MaxSizeSupported.Width / decoder.OrientedPixelWidth, MaxSizeSupported.Height/decoder.OrientedPixelHeight );
width =(uint)( decoder.OrientedPixelWidth * dScale);
height = (uint)(decoder.OrientedPixelHeight * dScale); tf.ScaledWidth = (uint)(decoder.PixelWidth* dScale);
tf.ScaledHeight = (uint)(decoder.PixelHeight* dScale);
} bitmap = new WriteableBitmap((int)width, (int)height); PixelDataProvider dataprovider = await decoder.GetPixelDataAsync(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Straight, tf,
ExifOrientationMode.RespectExifOrientation, ColorManagementMode.DoNotColorManage);
byte[] pixels = dataprovider.DetachPixelData(); Stream pixelStream2 = bitmap.PixelBuffer.AsStream(); pixelStream2.Write(pixels, , pixels.Length);
//bitmap.SetSource(fileStream);
}
catch
{
} return bitmap;
} public async static Task<WriteableBitmap> ReadBitmap(StorageFile file)
{
IRandomAccessStream stream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);
WriteableBitmap bitmap = await ReadBitmap(stream, file.FileType.ToLower()); return bitmap;
} public async static Task<bool> SaveBitmap(IRandomAccessStream stream, Guid encoderId, WriteableBitmap bitmap, BitmapTransform bitmapTransform)
{
bool bSuccess = true;
try
{
Stream pixelStream = bitmap.PixelBuffer.AsStream(); BitmapEncoder encoder = await BitmapEncoder.CreateAsync(encoderId, stream);
if (bitmapTransform != null)
{
encoder.BitmapTransform.ScaledWidth = bitmapTransform.ScaledWidth;
encoder.BitmapTransform.ScaledHeight = bitmapTransform.ScaledHeight;
encoder.BitmapTransform.InterpolationMode = BitmapInterpolationMode.Fant;
encoder.BitmapTransform.Bounds = bitmapTransform.Bounds;
} byte[] pixels = new byte[pixelStream.Length]; pixelStream.Read(pixels, , pixels.Length); encoder.SetPixelData(
BitmapPixelFormat.Bgra8,
BitmapAlphaMode.Straight,
(uint)bitmap.PixelWidth,
(uint)bitmap.PixelHeight,
, // Horizontal DPI
, // Vertical DPI
pixels
);
await encoder.FlushAsync(); pixelStream.Dispose();
}
catch
{
bSuccess = false;
} return bSuccess;
} async static Task<bool> SaveBitmap(StorageFile file, WriteableBitmap bitmap, BitmapTransform bitmapTransform)
{
bool bSuccess = true;
try
{
// Application now has read/write access to the saved file
Guid encoderId = EncoderIDFromFileExtension(file.FileType); IRandomAccessStream fileStream = await file.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite); bSuccess = await SaveBitmap(fileStream, encoderId,bitmap,bitmapTransform); fileStream.Dispose(); }
catch
{
bSuccess = false;
} return bSuccess;
} public async static Task<bool> SaveBitmap(StorageFile file, WriteableBitmap bitmap)
{
bool bSuccess = await SaveBitmap(file, bitmap, null);
return bSuccess;
} public async static Task<bool> SaveBitmapWithFilePicker(WriteableBitmap bitmap)
{
FileSavePicker save = new FileSavePicker();
save.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
save.DefaultFileExtension = ".jpg";
save.SuggestedFileName = "new image";
save.FileTypeChoices.Add(".bmp", new List<string>() { ".bmp" });
save.FileTypeChoices.Add(".png", new List<string>() { ".png" });
save.FileTypeChoices.Add(".jpg", new List<string>() { ".jpg", ".jpeg" }); StorageFile savedItem = await save.PickSaveFileAsync();
if (savedItem == null)
{
return false;
} return await SaveBitmap(savedItem, bitmap);
} public async static Task<bool> SaveBitmapAsThumb(StorageFile file, WriteableBitmap bitmap, double width, double height)
{
BitmapTransform transform = new BitmapTransform(); double ratio = Math.Min(width / bitmap.PixelWidth, height / bitmap.PixelHeight); transform.ScaledWidth = (uint)(bitmap.PixelWidth * ratio);
transform.ScaledHeight = (uint)(bitmap.PixelHeight * ratio);
transform.InterpolationMode = BitmapInterpolationMode.Fant; return await SaveBitmap(file, bitmap, transform);
}
public async static Task<bool> SaveBitmapAsThumb(StorageFile file, WriteableBitmap bitmap, Windows.Foundation.Rect cropRect)
{
BitmapTransform transform = new BitmapTransform(); double ratio =THumbLength/ Math.Max(cropRect.Width, cropRect.Height ); transform.ScaledWidth = (uint)(bitmap.PixelWidth * ratio);
transform.ScaledHeight = (uint)(bitmap.PixelHeight * ratio);
transform.Bounds = new BitmapBounds()
{
X = (uint)(cropRect.X * ratio),
Y = (uint)(cropRect.Y * ratio),
Width = (uint)(cropRect.Width * ratio),
Height = (uint)(cropRect.Height * ratio)
};
transform.InterpolationMode = BitmapInterpolationMode.Fant; return await SaveBitmap(file, bitmap, transform);
}
}
}

windows store app 读写图片的更多相关文章

  1. 05、Windows Store app 的图片裁切(更新)

    在 Win Phone Silverlight api 中,有一个 PhotoChooserTask 选择器,指定宽.高属性,在选择图片的时候, 可以进行裁切,代码: PhotoChooserTask ...

  2. 在桌面程序上和Metro/Modern/Windows store app的交互(相互打开,配置读取)

    这个标题真是取得我都觉得蛋疼..微软改名狂魔搞得我都不知道要叫哪个好.. 这边记录一下自己的桌面程序跟windows store app交互的过程. 由于某些原因,微软的商店应用的安全沙箱导致很多事情 ...

  3. Windows Store App 过渡动画

    Windows Store App 过渡动画     在开发Windows应用商店应用程序时,如果希望界面元素进入或者离开屏幕时显得自然和流畅,可以为其添加过渡动画.过渡动画能够及时地提示用户屏幕所发 ...

  4. Windows store app[Part 4]:深入WinRT的异步机制

    接上篇Windows store app[Part 3]:认识WinRT的异步机制 WinRT异步机制回顾: IAsyncInfo接口:WinRT下异步功能的核心,该接口提供所有异步操作的基本功能,如 ...

  5. Windows store app[Part 3]:认识WinRT的异步机制

    WinRT异步机制的诞生背景 当编写一个触控应用程序时,执行一个耗时函数,并通知UI更新,我们希望所有的交互过程都可以做出快速的反应.流畅的操作感变的十分重要. 在连接外部程序接口获取数据,操作本地数 ...

  6. 01、Windows Store APP 设置页面横竖屏的方法

    在 windows phone store app 中,判断和设置页面横竖屏的方法,与 silverlight 中的 Page 类 不同,不能直接通过 Page.Orientation 进行设置.而是 ...

  7. Windows store app[Part 1]:读取U盘数据

    Windows 8系统下开发App程序,对于.NET程序员来说,需要重新熟悉下类库. 关于WinRT,引用一张网上传的很多的结构图: 图1 针对App的开发,App工作在系统划定的安全沙箱内,所以通过 ...

  8. Windows Store App 偏移特效

    通过前面讲解的内容,读者已经了解了如何在三维空间中使旋转对象绕指定的旋转中心旋转一定的角度.接下来在这个基础上进一步讲解如何对旋转对象进行平移.下面首先介绍一下用到的几个属性. q  LocalOff ...

  9. Windows Store App 旋转中心

    旋转中心的位置可以通过设置CenterOfRotationX.CenterOfRotationY和CenterOfRotationZ属性来指定.CenterOfRotationX和CenterOfRo ...

随机推荐

  1. Redis 分区

    分区是分割数据到多个Redis实例的处理过程,因此每个实例只保存key的一个子集. 分区的优势 通过利用多台计算机内存的和值,允许我们构造更大的数据库. 通过多核和多台计算机,允许我们扩展计算能力:通 ...

  2. hadoop2 作业执行过程之reduce过程

    reduce阶段就是处理map的输出数据,大部分过程和map差不多 //ReduceTask.run方法开始和MapTask类似,包括initialize()初始化,根据情况看是否调用runJobCl ...

  3. EF——一对一、一对多、多对多关系的配置和级联删除 04(转)

    EF里一对一.一对多.多对多关系的配置和级联删除   本章节开始了解EF的各种关系.如果你对EF里实体间的各种关系还不是很熟悉,可以看看我的思路,能帮你更快的理解. I.实体间一对一的关系 添加一个P ...

  4. [SEO] 网站标题分隔符

    标题用什么分隔符对SEO最有利 我们在看同行的朋友对网站标题优化时,关键词分按照主次的顺序进行分布,在网站标题或者是关键词之间都会有一个符号,俗话来讲就称为关键词分隔符,网站标 题分隔符分为“-”(横 ...

  5. [JAVA] HTTP请求,返回响应内容,实例及应用

    JDK 中提供了一些对无状态协议请求(HTTP )的支持,下面我就将我所写的一个小例子(组件)进行描述: 首先让我们先构建一个请求类(HttpRequester ). 该类封装了 JAVA 实现简单请 ...

  6. JS实现滚动条滚到页面距离底部300px时执行事件的方法

    scrollTop为滚动条在Y轴上的滚动距离. clientHeight为内容可视区域的高度. scrollHeight为内容可视区域的高度加上溢出(滚动)的距离 $(window).scroll(f ...

  7. Oracle 11g XE 试用记录

    安装之前先删除系统环境变量中的oracle_home等配置(如果存在的话): 如果安装后出现Web管理界面不能访问或者数据库不能连接的情况,卸载再多安装几次可能就正常了.状态不正常时,可以使用 C:\ ...

  8. [转]position:relative leaves an empty space

    本文转自:http://stackoverflow.com/questions/5229081/positionrelative-leaves-an-empty-space 在使用relative进行 ...

  9. 用户体验测试(UE测试)

    用户体验测试(UE测试) 在测试周期早些时候就开始用户体验测试很明智.多数人往往会把UE测试放在最后,但UE测试可以揭示很多问题,如外观.字体.文本颜色.背景颜色.内容.布局等,还可以在测试周期尽可能 ...

  10. phpQuery用法

    了解phpQuery使用前了温习jquery.js的选择用法 jquery选择器,还有一个衍生产品QueryList 例: include 'phpQuery.php'; phpQuery::newD ...