问题
I am using a Report file and a ReportViewer control to show a report which loads data dynamically from objects during run-time.
I need to show an image which is stored as a byte array in the object.
The PictureBox's value is currently set to:
=First(Fields!ImageData.Value, "dtstItemImage")
And I set the DataSource using:
ImageBindingSource.DataSource = this.item.Image.ImageData;
The code compiles and runs but the image is not displayed in the report.
Is this because the PictureBox needs to be bound to an Image object (and not to a byte array)? Or are there perhaps some properties of the PictureBox which I need to set?
UPDATE 1
I've added a border to the PictureBox just to make sure that's its visible and it does show up in the report. It just doesn't contain the image.
UPDATE 2
I've fixed a mistake in my code. I've changed:
ImageBindingSource.DataSource = this.item.Image.ImageData;
to:
ImageBindingSource.DataSource = this.item.Image;
as the PictureBox is bound to the ImageData field BUT the DataSource is the Image object.
Now I get a small cross icon instead of nothing which (at least for me) indicates some progress but I don't know where the byte[]-bitmap conversion code needs to be.
回答1:
I managed to solve this by setting the report's Image box Source
property to Database
(it was previously set to External
).
More info about the different available Source values can be found at (MSDN) HowTo: Add an Image (Reporting Services).
回答2:
You need to create an image object from the byte array and use that as the source.
To do this, you can use a helper function like the following
public static Image LoadImage(byte[] imageBytes)
{
Image image = null;
using (var ms = new MemoryStream(imageBytes))
image = Image.FromStream(ms);
return image;
}
Edit
For WPF, you need to use BitmapSource
(MSDN) instead of Image
(MSDN)
public static BitmapSource LoadImage(Byte[] imageBytes)
{
var image = new BitmapImage();
using (var ms = new MemoryStream(binaryData))
{
image.BeginInit();
image.StreamSource = ms;
image.CacheOption = BitmapCacheOption.OnLoad;
image.EndInit();
}
if (image.CanFreeze)
image.Freeze();
return image;
}
NB: You can could also do this using a IValueConverter
, see this blog post for the source code.
and then modify your data binding
ImageBindingSource.DataSource = LoadImage(item.Image.ImageData);
...
Make sure that the image (and MemoryStream
) is disposed properly when you finished with it, as otherwise you will leak memory.
Also, depending on the format of your byte array you may need to do some work. See one of my question/answers for some helpful information.
来源:https://stackoverflow.com/questions/12319071/how-to-show-image-from-byte-array-in-microsoft-report