如何将NSImage或NSData设置为桌面映像? [英] How to set NSImage or NSData as Desktop Image?

查看:117
本文介绍了如何将NSImage或NSData设置为桌面映像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个NSImage(和它对应的NSData),我需要将该图像设置为桌面.

I have an NSImage (and it's corresponding NSData) and I need to set that image as the desktop. It seems that the only method APple provides for setting an image is

[NSWorkspace setDesktopImageURL:forScreen:options:error:]

如何从NSImage或NSData转换为NSURL?我这样做是为了保存imageData:

How can I convert from an NSImage or NSData to an NSURL? I am doing this to save the imageData:

[imageData writeToFile:@"wallpaper" atomically:NO]; 

但是如何获取该URL以便将其设置为桌面?我不知道如何获取保存到的URL.

But how can I get that URL in order to set it as the desktop? I can't figure out how to get the URL that it is saved to.

推荐答案

要准确回答您提出的问题:

To answer exactly the question you asked:

[NSURL fileURLWithPath:@"wallpaper"]

但是将文件实际写入传递给NSWorkspace的相同URL更为有意义,如下所示:

But it makes more sense to actually write the file to the same URL you pass to NSWorkspace, like this:

NSURL *url = [NSURL fileURLWithPath:@"wallpaper"];
[imageData writeToURL:url atomically:NO];
[[NSWorkspace sharedWorkspace] setDesktopImageURL:url …];

选择放置文件的好地方更加有意义.作为一般规则(即使在软件之外),如果您知道在哪里放置东西,则比只告诉某人将它``放到某处''要容易得多.而您特定的将其放置在某处"实际上意味着将其放置在当前工作目录中",这可能是您没有写访问权的地方,或者是用户不希望您混乱的地方,或者它可能已经拥有其中有一个称为墙纸"的文件(或目录),或者…

It makes even more sense to pick a good place to put the file. As a general rule (even outside of software), if you know where you put something, it's a lot easier to find it later than if you just tell someone "put this somewhere". And your specific "put this somewhere" really means "put this in the current working directory", which may be somewhere you don't have write access, or somewhere the user doesn't want you to clutter up, or it may already have a file (or a directory) called "wallpaper" in it, or…

因此,您可能想调用-[NSFileManager URLForDirectory:inDomain:appropriateForURL:create:error:]以获取NSTemporaryDirectory,或使用其他临时文件API.或者,您可能希望将其放置在应用程序的缓存目录中,而不是放置在临时位置中.一切对您来说都有意义.

So, you probably want to call -[NSFileManager URLForDirectory:inDomain:appropriateForURL:create:error:] to get the NSTemporaryDirectory, or use a different temp-file API. Or you might want to put it in your app's cache directory instead of a temporary location. Whatever seems to make sense to you.

此外,您可能想在文件上添加适当的扩展名.而且,在不知道您从何处获得imageData的情况下,我不确定您是否将获得可用的图像文件.但这都是单独的问题.

Also, you probably want to put an appropriate extension on the file. And, without knowing where you got imageData from, I'm not sure you're going to get a usable image file. But that's all separate issues.

这篇关于如何将NSImage或NSData设置为桌面映像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆