This is a migrated thread and some comments may be shown as answers.

Insert image from byte array

2 Answers 77 Views
RichTextBox
This is a migrated thread and some comments may be shown as answers.
naresh
Top achievements
Rank 1
naresh asked on 13 Mar 2012, 10:59 AM
Hi,
I have a probelm. In richtextbox I am able to inserting the image.
Its rendering with original size. 

private void AddImages(List<byte[]> productImages)
{
	foreach (var item in productImages)
{
this.rtbEditor.InsertImage(new MemoryStream(item),"png");
this.rtbEditor.Insert("   ");
}
}

But how to insert the images with fixed size (32 x 32) ?

Thanks for your help.

Thanks and Regards
Naresh Mesineni

2 Answers, 1 is accepted

Sort by
0
naresh
Top achievements
Rank 1
answered on 13 Mar 2012, 12:36 PM
Hey I got the solution. Here is code snippet
			foreach (var item in productImages)
{
BitmapFrame bfResize;
Stream streamPhoto = new MemoryStream(item);

BitmapFrame bfPhoto = ReadBitmapFrame(streamPhoto);
int nThumbnailSize = 48, nWidth, nHeight;
if (bfPhoto.Width > bfPhoto.Height)
{
nWidth = nThumbnailSize;
nHeight = (int)(bfPhoto.Height * nThumbnailSize / bfPhoto.Width);
}
else
{
nHeight = nThumbnailSize;
nWidth = (int)(bfPhoto.Width * nThumbnailSize / bfPhoto.Height);
}
bfResize = FastResize(bfPhoto, nWidth, nHeight);

using (MemoryStream memStream = new MemoryStream(ToByteArray(bfResize)))
{
this.rtbEditor.InsertImage(memStream, "PNG");
}
this.rtbEditor.Insert("   ");
}
		private BitmapFrame FastResize(BitmapFrame bfPhoto, int nWidth, int nHeight)
{
TransformedBitmap tbBitmap = new TransformedBitmap(bfPhoto, new ScaleTransform(nWidth / bfPhoto.Width, nHeight / bfPhoto.Height, 00));
return BitmapFrame.Create(tbBitmap);
}

private byte[] ToByteArray(BitmapFrame bfResize)
{
using (MemoryStream msStream = new MemoryStream())
{
PngBitmapEncoder pbdDecoder = new PngBitmapEncoder();
pbdDecoder.Frames.Add(bfResize);
pbdDecoder.Save(msStream);
return msStream.ToArray();
}
}

private BitmapFrame ReadBitmapFrame(Stream streamPhoto)
{
BitmapDecoder bdDecoder = BitmapDecoder.Create(streamPhoto, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.None);
return bdDecoder.Frames[0];
}
Thanks

Naresh Mesineni
0
Iva Toteva
Telerik team
answered on 13 Mar 2012, 12:46 PM
Hi Naresh,

It's good to hear that you have managed to find a way to resize the image.

A more straight-forward way would be to create an ImageInline object with the desired height and width and insert it with fixed width and height in the following way:

ImageInline image = new ImageInline(new MemoryStream(item), new Size(32, 32), "png");
this.rtbEditor.InsertInline(image);

I hope this helps.

Regards,
Iva Toteva
the Telerik team
Sharpen your .NET Ninja skills! Attend Q1 webinar week and get a chance to win a license! Book your seat now >>
Tags
RichTextBox
Asked by
naresh
Top achievements
Rank 1
Answers by
naresh
Top achievements
Rank 1
Iva Toteva
Telerik team
Share this question
or