Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HLScript/HeuristicLab.ExtLibs/HeuristicLab.EPPlus/3.1.3/EPPlus-3.1.3/ExcelBackgroundImage.cs @ 10331

Last change on this file since 10331 was 9580, checked in by sforsten, 12 years ago

#1730:

  • added SymbolicDataAnalysisExpressionExcelFormatter
  • changed modifiers in SymbolicExpressionTreeChart of methods SaveImageAsBitmap and SaveImageAsEmf to public
  • added menu item ExportSymbolicSolutionToExcelMenuItem to export a symbolic solution to an excel file
  • added EPPlus-3.1.3 to ExtLibs
File size: 6.7 KB
Line 
1/*******************************************************************************
2 * You may amend and distribute as you like, but don't remove this header!
3 *
4 * EPPlus provides server-side generation of Excel 2007/2010 spreadsheets.
5 * See http://www.codeplex.com/EPPlus for details.
6 *
7 * Copyright (C) 2011  Jan Källman
8 *
9 * This library is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Lesser General Public
11 * License as published by the Free Software Foundation; either
12 * version 2.1 of the License, or (at your option) any later version.
13
14 * This library is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 
17 * See the GNU Lesser General Public License for more details.
18 *
19 * The GNU Lesser General Public License can be viewed at http://www.opensource.org/licenses/lgpl-license.php
20 * If you unfamiliar with this license or have questions about it, here is an http://www.gnu.org/licenses/gpl-faq.html
21 *
22 * All code and executables are provided "as is" with no warranty either express or implied.
23 * The author accepts no liability for any damage or loss of business that this product may cause.
24 *
25 * Code change notes:
26 *
27 * Author             Change            Date
28 *******************************************************************************
29 * Jan Källman    Added   10-SEP-2009
30 * Jan Källman    License changed GPL-->LGPL 2011-12-16
31 *******************************************************************************/
32using System;
33using System.Collections.Generic;
34using System.Linq;
35using System.Text;
36using System.Xml;
37using System.Drawing;
38using System.IO.Packaging;
39using System.IO;
40using OfficeOpenXml.Drawing;
41namespace OfficeOpenXml
42{
43    /// <summary>
44    /// An image that fills the background of the worksheet.
45    /// </summary>
46    public class ExcelBackgroundImage : XmlHelper
47    {
48        ExcelWorksheet _workSheet;
49        /// <summary>
50        ///
51        /// </summary>
52        /// <param name="nsm"></param>
53        /// <param name="topNode">The topnode of the worksheet</param>
54        /// <param name="workSheet">Worksheet reference</param>
55        internal  ExcelBackgroundImage(XmlNamespaceManager nsm, XmlNode topNode, ExcelWorksheet workSheet) :
56            base(nsm, topNode)
57        {
58            _workSheet = workSheet;
59        }
60       
61        const string BACKGROUNDPIC_PATH = "d:picture/@r:id";
62        /// <summary>
63        /// The background image of the worksheet.
64        /// The image will be saved internally as a jpg.
65        /// </summary>
66        public Image Image
67        {
68            get
69            {
70                string relID = GetXmlNodeString(BACKGROUNDPIC_PATH);
71                if (!string.IsNullOrEmpty(relID))
72                {
73                    var rel = _workSheet.Part.GetRelationship(relID);
74                    var imagePart = _workSheet.Part.Package.GetPart(PackUriHelper.ResolvePartUri(rel.SourceUri, rel.TargetUri));
75                    return Image.FromStream(imagePart.GetStream());
76                }
77                return null;
78            }
79            set
80            {
81                DeletePrevImage();
82                if (value == null)
83                {
84                    DeleteAllNode(BACKGROUNDPIC_PATH);
85                }
86                else
87                {
88                    ImageConverter ic = new ImageConverter();
89                    byte[] img = (byte[])ic.ConvertTo(value, typeof(byte[]));
90                    var ii = _workSheet.Workbook._package.AddImage(img);
91                    var rel = _workSheet.Part.CreateRelationship(ii.Uri, TargetMode.Internal, ExcelPackage.schemaRelationships + "/image");
92                    SetXmlNodeString(BACKGROUNDPIC_PATH, rel.Id);
93                }
94            }
95        }
96        /// <summary>
97        /// Set the picture from an image file.
98        /// The image file will be saved as a blob, so make sure Excel supports the image format.
99        /// </summary>
100        /// <param name="PictureFile">The image file.</param>
101        public void SetFromFile(FileInfo PictureFile)
102        {
103            DeletePrevImage();
104
105            Image img;
106            try
107            {
108                img = Image.FromFile(PictureFile.FullName);
109            }
110            catch (Exception ex)
111            {
112                throw (new InvalidDataException("File is not a supported image-file or is corrupt", ex));
113            }
114
115            ImageConverter ic = new ImageConverter();
116            string contentType = ExcelPicture.GetContentType(PictureFile.Extension);
117            var imageURI = XmlHelper.GetNewUri(_workSheet._package.Package, "/xl/media/" + PictureFile.Name.Substring(0, PictureFile.Name.Length - PictureFile.Extension.Length) + "{0}" + PictureFile.Extension);
118
119            byte[] fileBytes = (byte[])ic.ConvertTo(img, typeof(byte[]));
120            var ii = _workSheet.Workbook._package.AddImage(fileBytes, imageURI, contentType);
121
122
123            if (_workSheet.Part.Package.PartExists(imageURI) && ii.RefCount==1) //The file exists with another content, overwrite it.
124            {
125                //Remove the part if it exists
126                _workSheet.Part.Package.DeletePart(imageURI);
127            }
128
129            var imagePart = _workSheet.Part.Package.CreatePart(imageURI, contentType, CompressionOption.NotCompressed);
130            //Save the picture to package.
131
132            var strm = imagePart.GetStream(FileMode.Create, FileAccess.Write);
133            strm.Write(fileBytes, 0, fileBytes.Length);
134
135            var rel = _workSheet.Part.CreateRelationship(imageURI, TargetMode.Internal, ExcelPackage.schemaRelationships + "/image");
136            SetXmlNodeString(BACKGROUNDPIC_PATH, rel.Id);
137        }
138        private void DeletePrevImage()
139        {
140            var relID = GetXmlNodeString(BACKGROUNDPIC_PATH);
141            if (relID != "")
142            {
143                var ic = new ImageConverter();
144                byte[] img = (byte[])ic.ConvertTo(Image, typeof(byte[]));
145                var ii = _workSheet.Workbook._package.GetImageInfo(img);
146
147                //Delete the relation
148                _workSheet.Part.DeleteRelationship(relID);
149               
150                //Delete the image if there are no other references.
151                if (ii != null && ii.RefCount == 1)
152                {
153                    if (_workSheet.Part.Package.PartExists(ii.Uri))
154                    {
155                        _workSheet.Part.Package.DeletePart(ii.Uri);
156                    }
157                }
158               
159            }
160        }
161    }
162}
Note: See TracBrowser for help on using the repository browser.