This is a migrated thread and some comments may be shown as answers.
Reducing file size
1 Answer 4 Views
This is a migrated thread and some comments may be shown as answers.
César
Top achievements
Rank 1
César asked on 16 Mar 2020, 12:52 PM
I'm exporting an list of people where the first column is a photo.

But regarless of changing the width/height the file size stays the same. Is there a way to reduce resolution ?

foreach (DataRow _dr in DS.Tables["PHOTO"].Rows)
          {
              FloatingImage image = new FloatingImage(sheet, new CellIndex(startRow, 0), 0, 0)
              {
                  ImageSource = new ImageSource((byte[])_dr["FOTO_EMPREGADO"], "jpg"),
                  Width = 65,
                  Height = 70
              };
 
              sheet.Shapes.Add(image);
 
              startRow++;
          }

1 Answer, 1 is accepted

Sort by
0
Martin
Telerik team
answered on 16 Mar 2020, 04:02 PM

Hi César,

If I understand you right you are loading these photos and you have access to them. If so, you can import them using System.Drawing.Image`s FromFile() method:

System.Drawing.Image image = Image.FromFile("sample.jpg");

and change their quality before importing them into the Workbook.

An approach for achieving this is to use the System.Drawing.Imaging.EncoderParameterin which constructor you can pass the Encoder.Quality and the desired quality (from 0 to 100). Check the following code snippet:

public static MemoryStream ReduceImageQualityAndAsMemorySteam(Image image, int quality)
{
	EncoderParameter qualityParam = new EncoderParameter(Encoder.Quality, quality);

	ImageCodecInfo jpegCodec = GetEncoderInfo("image/jpeg");
	EncoderParameters encoderParams = new EncoderParameters(1);
	encoderParams.Param[0] = qualityParam;

	MemoryStream memoryStream = new MemoryStream();
	image.Save(memoryStream, jpegCodec, encoderParams);

	return memoryStream;
}

private static ImageCodecInfo GetEncoderInfo(string mimeType)
{
	ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();

	for (int i = 0; i < codecs.Length; i++)
	{
		if (codecs[i].MimeType == mimeType)
		{
			return codecs[i];
		}
	}

	return null;
}

And when you have the image with reduced quality as Stream you can insert it in the Worksheet:

FloatingImage floatingImage = new FloatingImage(worksheet, new CellIndex(0, 0), 1, 1);
floatingImage.ImageSource = new Telerik.Windows.Documents.Media.ImageSource(imageStream, "jpg");

worksheet.Shapes.Add(floatingImage);

I hope this helps.

Regards,
Martin
Progress Telerik

Get quickly onboarded and successful with your Telerik and/or Kendo UI products with the Virtual Classroom free technical training, available to all active customers. Learn More.
Asked by
César
Top achievements
Rank 1
Answers by
Martin
Telerik team
Share this question
or