我需要您的帮助,将图像添加到 PDF。
我在用着:
string imgPath2 = localPath + "\\TempChartImages\\" + LegendPath;
img2.Save(imgPath2);
ith.WriteImage(imgPath2, 80);
但是这段代码给了我错误:
使用未分配的局部变量 img2
我该如何解决这个错误?
我需要您的帮助,将图像添加到 PDF。
我在用着:
string imgPath2 = localPath + "\\TempChartImages\\" + LegendPath;
img2.Save(imgPath2);
ith.WriteImage(imgPath2, 80);
但是这段代码给了我错误:
使用未分配的局部变量 img2
我该如何解决这个错误?
当您声明一个变量时,在您的情况下为 img2,没有分配一个值,它绝对没有指向任何东西。确保在使用 img2 之前将其初始化为某些内容。
我认为您希望将您的img2.Save
线路更改为:
Image img2 = Image.FromFile(yourInitialImageHere); // You could be reading from memory as well.
img2.Save(imgPath2);
不过,由于您的代码片段非常模糊,我可能会走得很远。
这是关于图像的 iTextSharp 教程。在没有看到更多代码的情况下,很难从中判断您需要哪段代码。
这是一种预感,但如果您在img2
Try-Catch 块内分配值,您可能会遇到阻止分配发生的异常。例如:
var img2;
try
{
var x = 5 / 0; // Generate a DivideByZero exception
img2 = GetImage(); // <-- the above exception will prevent this code from executing
}
catch
{
}
img2.Save(imgPath2); <-- img2 wasn't assigned, so another exception will occur
我相信你必须先实例化图像。
Image img2 = new Image();
它解决了我的问题。希望它能解决你的问题。
为此,您将需要一些第三方工具。
您必须创建图像的 getinstance。
iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance("path of the image");