Last active
December 15, 2019 22:45
-
-
Save nothke/da136796aa3f7d50559e4517a0c84ce8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// For this to work you need to copy these 2 files: | |
/// "YOUR UNITY LOCATION"\Editor\Data\Mono\lib\mono\X.X\System.Drawing.dll | |
/// "YOUR UNITY LOCATION"\Editor\Data\Mono\lib\mono\X.X\System.Windows.Forms.dll | |
/// ..to a "Plugins" folder within your project | |
/// | |
/// For this example to work, you need to have a (UI) Canvas object in your scene | |
/// Put this script on any object | |
/// | |
/// Tested on windows, not sure if it works on any other platform | |
/// | |
/// Original solution by Hellium found on http://answers.unity.com/answers/1499662/view.html | |
/// example by Nothke | |
/// | |
using UnityEngine; | |
using UnityEngine.UI; | |
public class ClipboardPasteImageExample : MonoBehaviour | |
{ | |
Canvas _canvas; | |
Canvas canvas { get { if (_canvas) return _canvas; else return FindObjectOfType<Canvas>(); } } | |
void Update() | |
{ | |
bool ctrl = Input.GetKey(KeyCode.LeftControl) || Input.GetKeyDown(KeyCode.RightControl); | |
if (ctrl && Input.GetKeyDown(KeyCode.V)) | |
CreateImageFromClipboard(); | |
} | |
void CreateImageFromClipboard() | |
{ | |
Texture2D texture = RetrieveFromClipboard(); | |
if (texture == null) return; | |
texture.wrapMode = TextureWrapMode.Clamp; | |
GameObject go = new GameObject("PastedImage"); | |
go.transform.SetParent(canvas.transform); | |
go.transform.position = Input.mousePosition; | |
go.AddComponent<CanvasRenderer>(); | |
RawImage image = go.AddComponent<RawImage>(); | |
image.texture = texture; | |
image.SetNativeSize(); | |
} | |
// Original solution by Hellium on http://answers.unity.com/answers/1499662/view.html | |
static Texture2D RetrieveFromClipboard() | |
{ | |
System.Drawing.Image image = System.Windows.Forms.Clipboard.GetImage(); | |
if (image == null) | |
{ | |
Debug.LogError("No image found in clipboard"); | |
return null; | |
} | |
System.IO.MemoryStream s = new System.IO.MemoryStream(image.Width * image.Height); | |
image.Save(s, System.Drawing.Imaging.ImageFormat.Png); | |
Texture2D texture = new Texture2D(image.Width, image.Height); | |
texture.LoadImage(s.ToArray()); | |
s.Close(); | |
s.Dispose(); | |
return texture; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment