using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Threading.Tasks;
using Windows.ApplicationModel;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media.Imaging;
namespace App110
{
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
Test();
}
private async void Test()
{
// Comparing image to itself should return true
Debug.Assert(await ComparePackageImages("Assets\\Logo.png", "Assets\\Logo.png"));
// "Copy of Logo.png" is "Logo.png" with changed one pixel
// and should return false when compared with "Logo.png"
Debug.Assert(!await ComparePackageImages("Assets\\Logo.png", "Assets\\Copy of Logo.png"));
// Two images of different size should
Debug.Assert(!await ComparePackageImages("Assets\\Logo.png", "Assets\\SmallLogo.png"));
await new MessageDialog("Success!").ShowAsync();
Application.Current.Exit();
}
private async Task<bool> ComparePackageImages(string packageFilePath1, string packageFilePath2)
{
var b1 = await LoadWriteableBitmapFromPackageFilePath(packageFilePath1);
var b2 = await LoadWriteableBitmapFromPackageFilePath(packageFilePath2);
var pixelStream1 = b1.PixelBuffer.AsStream();
var pixelStream2 = b2.PixelBuffer.AsStream();
return StreamEquals(pixelStream1, pixelStream2);
}
private static async Task<WriteableBitmap> LoadWriteableBitmapFromPackageFilePath(string packageFilePath1)
{
var bitmap = new WriteableBitmap(1, 1);
var storageFile = await Package.Current.InstalledLocation.GetFileAsync(packageFilePath1);
using (var streamWithContentType = await storageFile.OpenReadAsync())
{
await bitmap.SetSourceAsync(streamWithContentType);
}
return bitmap;
}
static bool StreamEquals(Stream stream1, Stream stream2)
{
const int bufferSize = 2048;
byte[] buffer1 = new byte[bufferSize]; //buffer size
byte[] buffer2 = new byte[bufferSize];
while (true)
{
int count1 = stream1.Read(buffer1, 0, bufferSize);
int count2 = stream2.Read(buffer2, 0, bufferSize);
if (count1 != count2)
return false;
if (count1 == 0)
return true;
// You might replace the following with an efficient "memcmp"
if (!buffer1.Take(count1).SequenceEqual(buffer2.Take(count2)))
return false;
}
}
}
}
Compare binary files in C#の好意によるストリーム比較。
WinRT XAML Toolkit提供のビットマップ アクセス コード スニペット。