我的任务是捕获图像,将其复制到剪贴板,然后将其粘贴到下面的应用程序中.我必须能够支持几乎任何富文本字段,并且它必须保留透明性.我当前的解决方案首先呈现白色背景.这是我的代码:RenderTargetBitmap包含要复制为....

我的任务是捕获图像,将其复制到剪贴板,然后将其粘贴到下面的应用程序中.我必须能够支持几乎任何富文本字段,并且它必须保留透明性.我当前的解决方案首先呈现白色背景.这是我的代码:
RenderTargetBitmap包含要复制为.PNG的图像
public static void CopyImageToClipboard(RenderTargetBitmap b)
{
MemoryStream stream = new MemoryStream();
PngBitmapEncoder encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(b));
encoder.Save(stream);
Bitmap bmp = new Bitmap(stream);
Bitmap blank = new Bitmap(Convert.ToInt32(b.Width), Convert.ToInt32(b.Height));
Graphics g = Graphics.FromImage(blank);
g.Clear(System.Drawing.Color.White);
System.Drawing.Image img = System.Drawing.Image.FromStream(stream);
g.DrawImage(img, 0, 0, Convert.ToInt32(b.Width), Convert.ToInt32(b.Height));
Bitmap tempImage = new Bitmap(blank);
blank.Dispose();
img.Dispose();
bmp = new Bitmap(tempImage);
tempImage.Dispose();
System.Windows.Forms.Clipboard.SetImage(bmp);
stream.Dispose();
}
解决方法:
假设随机选择一种颜色作为背景
var background = Color.FromArgb(1, 255, 1, 255);
清除背景:
g.Clear(background); // instead of System.Drawing.Color.White
然后使该颜色透明:
Bitmap tempImage = new Bitmap(blank);
tempImage.MakeTransparent(background);
请注意,默认的透明颜色也很好用,不需要选择魔术色(检查是否需要Clear()背景,可能是-我没有检查-默认位图背景):
g.Clear(Color.Transparent);
// ...
tempImage.MakeTransparent();
编辑一些较旧的RTF控件版本无法处理透明度,因此您无能为力(AFAIK).半透明的解决方法(如果无法检测到粘贴目标的控件类并读取其背景颜色)是使用Color.FromArgb(254,255,255,255).不支持透明的白色,并且由于完全透明(由于MakeTransparent())而完全透明.
织梦狗教程
本文标题为:C#Win8:将.PNG复制到Windows剪贴板;粘贴并保留透明性


基础教程推荐
猜你喜欢
- unity 如何获取Text组件里text内容的长度 2023-04-14
- c# – 为什么非托管内存占控制台应用程序使用的内存的60%以上? 2023-09-18
- C# 获取系统字体的示例代码 2023-03-04
- 10分钟 在linux里创建.net core helloworld控制台程序 2023-09-28
- C#机器入门学习之判断日报是否合格详解 2023-01-16
- .NET 平台负责人 Scott Hunter 专访:.NET Core 3 给 .NET Core 2023-09-27
- WPF实现动画效果(五)之关键帧动画 2023-06-21
- C#实现计算器窗体程序 2023-05-16
- LINQ基础之Intersect、Except和Distinct子句 2023-05-31
- 动手实现一个适用于.NET Core 的诊断工具 2023-09-28