六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 309|回复: 0

Windows Phone实用开发技巧(38):图片拼接

[复制链接]

升级  20%

24

主题

24

主题

24

主题

秀才

Rank: 2

积分
80
 楼主| 发表于 2012-12-22 02:43:33 | 显示全部楼层 |阅读模式
<div id="cnblogs_post_body">图片拼接是拼图中一种,即将若干图片拼接成一张大图。本文将讲述如何在windows phone中实现图片的拼接。
  首先,我们准备一些拼图的原始图片,这些图片的长度、宽度各不一样,并且也不是等比例。
  private int width = 480;private int totalHeight = 0;string[] array = new string[] { "1.jpg", "2.jpg", "3.jpg", "4.jpg" };WriteableBitmap[] imagearray;int[] heightarray;一些常量的定义,array数组存储的是待拼接的图片列表
imagearray存储的是图片对应的WriteableBitamp对象
heightarray存储的是图片按比例缩放后的高度(宽度都为480)
totalHeight表示图片拼接后的总高度
我们在页面中方式一个ScrollViewer,然后将图片都放置在一个Canvas中,设置图片的距离顶部距离,最后将Canvas方式到ScrollViewer中:
private void Join(){    //images container    Canvas canvas = new Canvas();    //init array    imagearray = new WriteableBitmap[array.Length];    heightarray = new int[array.Length];    for (int i = 0; i < array.Length; i++)    {        WriteableBitmap bitmap = FromContent(string.Format("Images/{0}", array));        double wr = width / (double)bitmap.PixelWidth;        int height = (int)(bitmap.PixelHeight * wr);        Image img = new Image() { Source = bitmap, Stretch = Stretch.Fill, Width = width, Height = height };        Canvas.SetLeft(img, 0);        Canvas.SetTop(img, totalHeight);        canvas.Children.Add(img);        totalHeight += height;        imagearray = bitmap;        heightarray = height;    }    canvas.Height = totalHeight;    scrollviewer.Content = canvas;}其中需要注意的就是将图片按比例缩放,为了防止保存图片时候重新计算一遍高度,我们将高度和图片保存到数据中。
下面来看一下保存的方法,我们需要得到一个ScrollViewer的WriteableBitmap,那么能不能使用直接对UI元素的截屏呢?答案是否定的,因为截屏我们只能得到屏幕大小的图片,不能得到整个长图。
那么我们应该怎么做呢,其实思路跟上面的展示方式一样,我们将图片拼接起来,具体的代码如下:
//遍历,将每张图copy至大图的相应位置WriteableBitmap output = new WriteableBitmap(width, totalHeight);int toTop = 0;for (int i = 0; i < imagearray.Length; i++){    var wb = imagearray.Resize(width, heightarray, WriteableBitmapExtensions.Interpolation.NearestNeighbor);    Rect dest = new Rect(0, toTop, width, heightarray);    Rect source = new Rect(0, 0, width, heightarray);    output.Blit(dest, wb, source);    toTop += heightarray;}SaveImage(output);遍历图片,将图片copy至一张大图的某些部分
保存方法是将图片保存到相册中,当然我们也可以保存到独立存储空间中:
private void SaveImage(WriteableBitmap bit){    string msg = "";    try    {        byte[] imageBuffer;        using (MemoryStream memoryStream = new MemoryStream())        {            bit.SaveJpeg(memoryStream, bit.PixelWidth, bit.PixelHeight, 0, 100);            imageBuffer = memoryStream.ToArray();        }        using (MediaLibrary library = new MediaLibrary())        {            library.SavePicture(string.Format("{0}.jpg", DateTime.Now.ToFileTime().ToString()), imageBuffer);        }        msg = "保存成功";    }    catch (Exception ex)    {        msg = "保存失败";    }    finally    {        MessageBox.Show(msg);    }}源代码你可以在这里找到.
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表