我一直在开发一个应用程序,将Microsoft Bing图像设置为壁纸,但由于某种原因,该代码在移动设备上有效,但在桌面上似乎不起作用。
以下是设置壁纸的主要代码:
注意: imageViewModel.Bitmap是可写位图的一种
const string fileName = "start_temp.jpg";
var file = await ApplicationData.Current.LocalFolder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);
using (IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.ReadWrite))
{
BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, stream);
Stream pixelStream = imageViewModel.Bitmap.PixelBuffer.AsStream();
byte[] pixels = new byte[pixelStream.Length];
await pixelStream.ReadAsync(pixels, 0, pixels.Length);
encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore,
(uint)imageViewModel.Bitmap.PixelWidth, (uint)imageViewModel.Bitmap.PixelHeight, 96.0, 96.0, pixels);
await encoder.FlushAsync();
}
if (await Windows.System.UserProfile.UserProfilePersonalizationSettings.Current.TrySetWallpaperImageAsync(file))
{
showToastNotification("Start background image set successfull!");
}
这些代码在手机上运行得很好,但在台式机上却不一样。我已使用UserProfilePersonalizationSettings.IsSupported()并确认设备受支持。
有一个可行的场景:
- 首先将WriteableBitmap保存为类似桌面的jpg图像
- 将jpg图像复制到ApplicationData.Current.LocalFolder
- 最后使用TrySetWallpaperImageAsync(…)设置壁纸
我不知道为什么上面的代码在桌面上不起作用=(
以下是我如何下载图像的代码:
private async Task<WriteableBitmap> loadImage(string url)
{
var response = await new HttpClient().GetAsync(url);
byte[] imageByte = await response.Content.ReadAsByteArrayAsync();
WriteableBitmap bitmap = new WriteableBitmap(1920, 1080);
using (InMemoryRandomAccessStream randomStream = new InMemoryRandomAccessStream())
{
using (DataWriter writer = new DataWriter(randomStream))
{
writer.WriteBytes(imageByte);
await writer.StoreAsync();
await writer.FlushAsync();
writer.DetachStream();
}
randomStream.Seek(0);
await bitmap.SetSourceAsync(randomStream);
}
return bitmap;
}
在两种不同的设备上测试了我的应用程序并运行良好后,我的电脑似乎出现了TrySetWallpaperImageAsync
或TrySetLockscreenImageAsync
API问题。
经过一些研究,问题是开发人员环境问题,我电脑上的Visual Studio/Windows SDK在运行代码时遇到了一些问题。
我部署了一个软件包并将其安装在我的电脑上,一切都很好。