/// <summary> /// Inserts a picture at the end of the text in the header or footer /// </summary> /// <param name="PictureFile">The image object containing the Picture</param> /// <param name="Alignment">Alignment. The image object will be inserted at the end of the Text.</param> public ExcelVmlDrawingPicture InsertPicture(FileInfo PictureFile, PictureAlignment Alignment) { string id = ValidateImage(Alignment); Image Picture; try { if (!PictureFile.Exists) { throw (new FileNotFoundException(string.Format("{0} is missing", PictureFile.FullName))); } Picture = Image.FromFile(PictureFile.FullName); } catch (Exception ex) { throw (new InvalidDataException("File is not a supported image-file or is corrupt", ex)); } string contentType = ExcelPicture.GetContentType(PictureFile.Extension); var uriPic = XmlHelper.GetNewUri(_ws._package.Package, "/xl/media/" + PictureFile.Name.Substring(0, PictureFile.Name.Length - PictureFile.Extension.Length) + "{0}" + PictureFile.Extension); #if (Core) var imgBytes = ImageCompat.GetImageAsByteArray(Picture); #else var ic = new ImageConverter(); byte[] imgBytes = (byte[])ic.ConvertTo(Picture, typeof(byte[])); #endif var ii = _ws.Workbook._package.AddImage(imgBytes, uriPic, contentType); return(AddImage(Picture, id, ii)); }
/// <summary> /// Set the picture from an image file. /// The image file will be saved as a blob, so make sure Excel supports the image format. /// </summary> /// <param name="PictureFile">The image file.</param> public void SetFromFile(FileInfo PictureFile) { DeletePrevImage(); Image img; try { img = Image.FromFile(PictureFile.FullName); } catch (Exception ex) { throw (new InvalidDataException("File is not a supported image-file or is corrupt", ex)); } ImageConverter ic = new ImageConverter(); string contentType = ExcelPicture.GetContentType(PictureFile.Extension); var imageURI = XmlHelper.GetNewUri(_workSheet._package.Package, "/xl/media/" + PictureFile.Name.Substring(0, PictureFile.Name.Length - PictureFile.Extension.Length) + "{0}" + PictureFile.Extension); byte[] fileBytes = (byte[])ic.ConvertTo(img, typeof(byte[])); var ii = _workSheet.Workbook._package.AddImage(fileBytes, imageURI, contentType); if (_workSheet.Part.Package.PartExists(imageURI) && ii.RefCount == 1) //The file exists with another content, overwrite it. { //Remove the part if it exists _workSheet.Part.Package.DeletePart(imageURI); } var imagePart = _workSheet.Part.Package.CreatePart(imageURI, contentType, CompressionOption.NotCompressed); //Save the picture to package. var strm = imagePart.GetStream(FileMode.Create, FileAccess.Write); strm.Write(fileBytes, 0, fileBytes.Length); var rel = _workSheet.Part.CreateRelationship(imageURI, TargetMode.Internal, ExcelPackage.schemaRelationships + "/image", PackagePartForMono.NextRelationshipID); SetXmlNodeString(BACKGROUNDPIC_PATH, rel.Id); }