Silverlight &Windows phone7 中使用Isolated Storage存储与读取图片

链接地址:http://www.cnblogs.com/xingchen/admin/EditPosts.aspx?opt=1

1.将ImageSource转化成WriteableBitmap

var bitmap= new System.Windows.Media.Imaging.WriteableBitmap((System.Windows.Media.Imaging.BitmapSource)this.imgCreatedTag.Source);

2.代码:
 

   
     

/// <summary>
/// 载入指定名称的图片
/// </summary>
/// <param name="fileName"></param>
/// <returns> 返回指定文件的byte[]流 </returns>
private static byte [] _LoadIfExists( string fileName)
{
byte [] retVal;

using (IsolatedStorageFile iso = IsolatedStorageFile.GetUserStoreForApplication())
{
if (iso.FileExists(fileName))
{
using (IsolatedStorageFileStream stream =
iso.OpenFile(fileName, FileMode.Open))
{
retVal
= new byte [stream.Length];
stream.Read(retVal,
0 , retVal.Length);
}
}
else
{
retVal
= new byte [ 0 ];
}
}
return retVal;
}
/// <summary>
/// 保存byte[]流到Storage
/// </summary>
/// <param name="buffer"></param>
/// <param name="fileName"></param>
private static void _SaveToDisk( byte [] buffer, string fileName)
{
using (IsolatedStorageFile iso =
IsolatedStorageFile.GetUserStoreForApplication())
{
using (
IsolatedStorageFileStream stream
=
new IsolatedStorageFileStream(fileName, FileMode.CreateNew,
iso))
{
stream.Write(buffer,
0 , buffer.Length);
}
}
}
/// <summary>
/// 从Storage获取图片
/// </summary>
/// <param name="buffer"> 图片的byte[]流 </param>
/// <returns></returns>
private static WriteableBitmap _GetImage( byte [] buffer)
{
int width = buffer[ 0 ] * 256 + buffer[ 1 ];
int height = buffer[ 2 ] * 256 + buffer[ 3 ];

long matrixSize = width * height;

WriteableBitmap retVal
= new WriteableBitmap(width, height);

int bufferPos = 4 ;

for ( int matrixPos = 0 ; matrixPos < matrixSize; matrixPos ++ )
{
int pixel = buffer[bufferPos ++ ];
pixel
= pixel << 8 | buffer[bufferPos ++ ];
pixel
= pixel << 8 | buffer[bufferPos ++ ];
pixel
= pixel << 8 | buffer[bufferPos ++ ];
retVal.Pixels[matrixPos]
= pixel;
}

return retVal;
}

/// <summary>
/// 将图片转换成byte[]流
/// </summary>
/// <param name="bitmap"></param>
/// <returns></returns>
private static byte [] _GetSaveBuffer(WriteableBitmap bitmap)
{
long matrixSize = bitmap.PixelWidth * bitmap.PixelHeight;

long byteSize = matrixSize * 4 + 4 ;

byte [] retVal = new byte [byteSize];

long bufferPos = 0 ;

retVal[bufferPos
++ ] = ( byte )((bitmap.PixelWidth / 256 ) & 0xff );
retVal[bufferPos
++ ] = ( byte )((bitmap.PixelWidth % 256 ) & 0xff );
retVal[bufferPos
++ ] = ( byte )((bitmap.PixelHeight / 256 ) & 0xff );
retVal[bufferPos
++ ] = ( byte )((bitmap.PixelHeight % 256 ) & 0xff );

for ( int matrixPos = 0 ; matrixPos < matrixSize; matrixPos ++ )
{
retVal[bufferPos
++ ] = ( byte )((bitmap.Pixels[matrixPos] >> 24 ) & 0xff );
retVal[bufferPos
++ ] = ( byte )((bitmap.Pixels[matrixPos] >> 16 ) & 0xff );
retVal[bufferPos
++ ] = ( byte )((bitmap.Pixels[matrixPos] >> 8 ) & 0xff );
retVal[bufferPos
++ ] = ( byte )((bitmap.Pixels[matrixPos]) & 0xff );
}

return retVal;
}

你可能感兴趣的:(windows phone)