Other API Samples C# logo

Embed Picture In Chart SpreadsheetGear API Sample

Description

Demonstrates how to embed a picture into a chart, in this case to act as a replacement for the Chart Title.

Sample Source Code

// Open workbook with a chart and get reference to active worksheet.
SpreadsheetGear.IWorkbook workbook = 
    SpreadsheetGear.Factory.GetWorkbook(@"Files\WorkbookWithChart.xlsx");
SpreadsheetGear.IWorksheet worksheet = workbook.ActiveWorksheet;

// Load picture into byte array (would also accept path to a file).
byte[] pictureBytes = 
    System.IO.File.ReadAllBytes(@"Files\SpreadsheetGearLogoAndText.png");
            
// Open the file as a System.Drawing.Image so that we can get its dimensions, and
// more important, the proportion between the height and width.
System.IO.MemoryStream ms = new System.IO.MemoryStream(pictureBytes);
System.Drawing.Image image = System.Drawing.Image.FromStream(ms);
double imageWidth = image.Width;
double imageHeight = image.Height;
double imageProportion = imageHeight / imageWidth;

// Get the Chart IShape and IChart objects.
SpreadsheetGear.Shapes.IShape chartShape = worksheet.Shapes["Chart 1"];
SpreadsheetGear.Charts.IChart chart = chartShape.Chart;

// Calculate size and position of picture so that it fills 75% of the  chart's
// total width, and is centered at the top of the chart.
double width = chartShape.Width * 0.75;
double height = width * imageProportion;
double left = (chartShape.Width - width) / 2;
double top = 5;
            
// Embed the picture.
chart.Shapes.AddPicture(pictureBytes, left, top, width, height);