picture.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629
  1. // Copyright 2016 - 2020 The excelize Authors. All rights reserved. Use of
  2. // this source code is governed by a BSD-style license that can be found in
  3. // the LICENSE file.
  4. //
  5. // Package excelize providing a set of functions that allow you to write to
  6. // and read from XLSX files. Support reads and writes XLSX file generated by
  7. // Microsoft Excel™ 2007 and later. Support save file without losing original
  8. // charts of XLSX. This library needs Go version 1.10 or later.
  9. package excelize
  10. import (
  11. "bytes"
  12. "encoding/json"
  13. "encoding/xml"
  14. "errors"
  15. "fmt"
  16. "image"
  17. "io"
  18. "io/ioutil"
  19. "os"
  20. "path"
  21. "path/filepath"
  22. "strconv"
  23. "strings"
  24. )
  25. // parseFormatPictureSet provides a function to parse the format settings of
  26. // the picture with default value.
  27. func parseFormatPictureSet(formatSet string) (*formatPicture, error) {
  28. format := formatPicture{
  29. FPrintsWithSheet: true,
  30. FLocksWithSheet: false,
  31. NoChangeAspect: false,
  32. Autofit: false,
  33. OffsetX: 0,
  34. OffsetY: 0,
  35. XScale: 1.0,
  36. YScale: 1.0,
  37. }
  38. err := json.Unmarshal(parseFormatSet(formatSet), &format)
  39. return &format, err
  40. }
  41. // AddPicture provides the method to add picture in a sheet by given picture
  42. // format set (such as offset, scale, aspect ratio setting and print settings)
  43. // and file path. For example:
  44. //
  45. // package main
  46. //
  47. // import (
  48. // _ "image/gif"
  49. // _ "image/jpeg"
  50. // _ "image/png"
  51. //
  52. // "github.com/360EntSecGroup-Skylar/excelize"
  53. // )
  54. //
  55. // func main() {
  56. // f := excelize.NewFile()
  57. // // Insert a picture.
  58. // if err := f.AddPicture("Sheet1", "A2", "image.jpg", ""); err != nil {
  59. // fmt.Println(err)
  60. // }
  61. // // Insert a picture scaling in the cell with location hyperlink.
  62. // if err := f.AddPicture("Sheet1", "D2", "image.png", `{"x_scale": 0.5, "y_scale": 0.5, "hyperlink": "#Sheet2!D8", "hyperlink_type": "Location"}`); err != nil {
  63. // fmt.Println(err)
  64. // }
  65. // // Insert a picture offset in the cell with external hyperlink, printing and positioning support.
  66. // if err := f.AddPicture("Sheet1", "H2", "image.gif", `{"x_offset": 15, "y_offset": 10, "hyperlink": "https://github.com/360EntSecGroup-Skylar/excelize", "hyperlink_type": "External", "print_obj": true, "lock_aspect_ratio": false, "locked": false, "positioning": "oneCell"}`); err != nil {
  67. // fmt.Println(err)
  68. // }
  69. // if err := f.SaveAs("Book1.xlsx"); err != nil {
  70. // fmt.Println(err)
  71. // }
  72. // }
  73. //
  74. // LinkType defines two types of hyperlink "External" for web site or
  75. // "Location" for moving to one of cell in this workbook. When the
  76. // "hyperlink_type" is "Location", coordinates need to start with "#".
  77. //
  78. // Positioning defines two types of the position of a picture in an Excel
  79. // spreadsheet, "oneCell" (Move but don't size with cells) or "absolute"
  80. // (Don't move or size with cells). If you don't set this parameter, default
  81. // positioning is move and size with cells.
  82. func (f *File) AddPicture(sheet, cell, picture, format string) error {
  83. var err error
  84. // Check picture exists first.
  85. if _, err = os.Stat(picture); os.IsNotExist(err) {
  86. return err
  87. }
  88. ext, ok := supportImageTypes[path.Ext(picture)]
  89. if !ok {
  90. return errors.New("unsupported image extension")
  91. }
  92. file, _ := ioutil.ReadFile(picture)
  93. _, name := filepath.Split(picture)
  94. return f.AddPictureFromBytes(sheet, cell, format, name, ext, file)
  95. }
  96. // AddPictureFromBytes provides the method to add picture in a sheet by given
  97. // picture format set (such as offset, scale, aspect ratio setting and print
  98. // settings), file base name, extension name and file bytes. For example:
  99. //
  100. // package main
  101. //
  102. // import (
  103. // "fmt"
  104. // _ "image/jpeg"
  105. // "io/ioutil"
  106. //
  107. // "github.com/360EntSecGroup-Skylar/excelize"
  108. // )
  109. //
  110. // func main() {
  111. // f := excelize.NewFile()
  112. //
  113. // file, err := ioutil.ReadFile("image.jpg")
  114. // if err != nil {
  115. // fmt.Println(err)
  116. // }
  117. // if err := f.AddPictureFromBytes("Sheet1", "A2", "", "Excel Logo", ".jpg", file); err != nil {
  118. // fmt.Println(err)
  119. // }
  120. // if err := f.SaveAs("Book1.xlsx"); err != nil {
  121. // fmt.Println(err)
  122. // }
  123. // }
  124. //
  125. func (f *File) AddPictureFromBytes(sheet, cell, format, name, extension string, file []byte) error {
  126. var drawingHyperlinkRID int
  127. var hyperlinkType string
  128. ext, ok := supportImageTypes[extension]
  129. if !ok {
  130. return errors.New("unsupported image extension")
  131. }
  132. formatSet, err := parseFormatPictureSet(format)
  133. if err != nil {
  134. return err
  135. }
  136. img, _, err := image.DecodeConfig(bytes.NewReader(file))
  137. if err != nil {
  138. return err
  139. }
  140. // Read sheet data.
  141. xlsx, err := f.workSheetReader(sheet)
  142. if err != nil {
  143. return err
  144. }
  145. // Add first picture for given sheet, create xl/drawings/ and xl/drawings/_rels/ folder.
  146. drawingID := f.countDrawings() + 1
  147. drawingXML := "xl/drawings/drawing" + strconv.Itoa(drawingID) + ".xml"
  148. drawingID, drawingXML = f.prepareDrawing(xlsx, drawingID, sheet, drawingXML)
  149. drawingRels := "xl/drawings/_rels/drawing" + strconv.Itoa(drawingID) + ".xml.rels"
  150. mediaStr := ".." + strings.TrimPrefix(f.addMedia(file, ext), "xl")
  151. drawingRID := f.addRels(drawingRels, SourceRelationshipImage, mediaStr, hyperlinkType)
  152. // Add picture with hyperlink.
  153. if formatSet.Hyperlink != "" && formatSet.HyperlinkType != "" {
  154. if formatSet.HyperlinkType == "External" {
  155. hyperlinkType = formatSet.HyperlinkType
  156. }
  157. drawingHyperlinkRID = f.addRels(drawingRels, SourceRelationshipHyperLink, formatSet.Hyperlink, hyperlinkType)
  158. }
  159. err = f.addDrawingPicture(sheet, drawingXML, cell, name, img.Width, img.Height, drawingRID, drawingHyperlinkRID, formatSet)
  160. if err != nil {
  161. return err
  162. }
  163. f.addContentTypePart(drawingID, "drawings")
  164. return err
  165. }
  166. // deleteSheetRelationships provides a function to delete relationships in
  167. // xl/worksheets/_rels/sheet%d.xml.rels by given worksheet name and
  168. // relationship index.
  169. func (f *File) deleteSheetRelationships(sheet, rID string) {
  170. name, ok := f.sheetMap[trimSheetName(sheet)]
  171. if !ok {
  172. name = strings.ToLower(sheet) + ".xml"
  173. }
  174. var rels = "xl/worksheets/_rels/" + strings.TrimPrefix(name, "xl/worksheets/") + ".rels"
  175. sheetRels := f.relsReader(rels)
  176. if sheetRels == nil {
  177. sheetRels = &xlsxRelationships{}
  178. }
  179. for k, v := range sheetRels.Relationships {
  180. if v.ID == rID {
  181. sheetRels.Relationships = append(sheetRels.Relationships[:k], sheetRels.Relationships[k+1:]...)
  182. }
  183. }
  184. f.Relationships[rels] = sheetRels
  185. }
  186. // addSheetLegacyDrawing provides a function to add legacy drawing element to
  187. // xl/worksheets/sheet%d.xml by given worksheet name and relationship index.
  188. func (f *File) addSheetLegacyDrawing(sheet string, rID int) {
  189. xlsx, _ := f.workSheetReader(sheet)
  190. xlsx.LegacyDrawing = &xlsxLegacyDrawing{
  191. RID: "rId" + strconv.Itoa(rID),
  192. }
  193. }
  194. // addSheetDrawing provides a function to add drawing element to
  195. // xl/worksheets/sheet%d.xml by given worksheet name and relationship index.
  196. func (f *File) addSheetDrawing(sheet string, rID int) {
  197. xlsx, _ := f.workSheetReader(sheet)
  198. xlsx.Drawing = &xlsxDrawing{
  199. RID: "rId" + strconv.Itoa(rID),
  200. }
  201. }
  202. // addSheetPicture provides a function to add picture element to
  203. // xl/worksheets/sheet%d.xml by given worksheet name and relationship index.
  204. func (f *File) addSheetPicture(sheet string, rID int) {
  205. xlsx, _ := f.workSheetReader(sheet)
  206. xlsx.Picture = &xlsxPicture{
  207. RID: "rId" + strconv.Itoa(rID),
  208. }
  209. }
  210. // countDrawings provides a function to get drawing files count storage in the
  211. // folder xl/drawings.
  212. func (f *File) countDrawings() int {
  213. c1, c2 := 0, 0
  214. for k := range f.XLSX {
  215. if strings.Contains(k, "xl/drawings/drawing") {
  216. c1++
  217. }
  218. }
  219. for rel := range f.Drawings {
  220. if strings.Contains(rel, "xl/drawings/drawing") {
  221. c2++
  222. }
  223. }
  224. if c1 < c2 {
  225. return c2
  226. }
  227. return c1
  228. }
  229. // addDrawingPicture provides a function to add picture by given sheet,
  230. // drawingXML, cell, file name, width, height relationship index and format
  231. // sets.
  232. func (f *File) addDrawingPicture(sheet, drawingXML, cell, file string, width, height, rID, hyperlinkRID int, formatSet *formatPicture) error {
  233. col, row, err := CellNameToCoordinates(cell)
  234. if err != nil {
  235. return err
  236. }
  237. if formatSet.Autofit {
  238. width, height, col, row, err = f.drawingResize(sheet, cell, float64(width), float64(height), formatSet)
  239. if err != nil {
  240. return err
  241. }
  242. }
  243. col--
  244. row--
  245. colStart, rowStart, _, _, colEnd, rowEnd, x2, y2 :=
  246. f.positionObjectPixels(sheet, col, row, formatSet.OffsetX, formatSet.OffsetY, width, height)
  247. content, cNvPrID := f.drawingParser(drawingXML)
  248. twoCellAnchor := xdrCellAnchor{}
  249. twoCellAnchor.EditAs = formatSet.Positioning
  250. from := xlsxFrom{}
  251. from.Col = colStart
  252. from.ColOff = formatSet.OffsetX * EMU
  253. from.Row = rowStart
  254. from.RowOff = formatSet.OffsetY * EMU
  255. to := xlsxTo{}
  256. to.Col = colEnd
  257. to.ColOff = x2 * EMU
  258. to.Row = rowEnd
  259. to.RowOff = y2 * EMU
  260. twoCellAnchor.From = &from
  261. twoCellAnchor.To = &to
  262. pic := xlsxPic{}
  263. pic.NvPicPr.CNvPicPr.PicLocks.NoChangeAspect = formatSet.NoChangeAspect
  264. pic.NvPicPr.CNvPr.ID = cNvPrID
  265. pic.NvPicPr.CNvPr.Descr = file
  266. pic.NvPicPr.CNvPr.Name = "Picture " + strconv.Itoa(cNvPrID)
  267. if hyperlinkRID != 0 {
  268. pic.NvPicPr.CNvPr.HlinkClick = &xlsxHlinkClick{
  269. R: SourceRelationship,
  270. RID: "rId" + strconv.Itoa(hyperlinkRID),
  271. }
  272. }
  273. pic.BlipFill.Blip.R = SourceRelationship
  274. pic.BlipFill.Blip.Embed = "rId" + strconv.Itoa(rID)
  275. pic.SpPr.PrstGeom.Prst = "rect"
  276. twoCellAnchor.Pic = &pic
  277. twoCellAnchor.ClientData = &xdrClientData{
  278. FLocksWithSheet: formatSet.FLocksWithSheet,
  279. FPrintsWithSheet: formatSet.FPrintsWithSheet,
  280. }
  281. content.TwoCellAnchor = append(content.TwoCellAnchor, &twoCellAnchor)
  282. f.Drawings[drawingXML] = content
  283. return err
  284. }
  285. // countMedia provides a function to get media files count storage in the
  286. // folder xl/media/image.
  287. func (f *File) countMedia() int {
  288. count := 0
  289. for k := range f.XLSX {
  290. if strings.Contains(k, "xl/media/image") {
  291. count++
  292. }
  293. }
  294. return count
  295. }
  296. // addMedia provides a function to add a picture into folder xl/media/image by
  297. // given file and extension name. Duplicate images are only actually stored once
  298. // and drawings that use it will reference the same image.
  299. func (f *File) addMedia(file []byte, ext string) string {
  300. count := f.countMedia()
  301. for name, existing := range f.XLSX {
  302. if !strings.HasPrefix(name, "xl/media/image") {
  303. continue
  304. }
  305. if bytes.Equal(file, existing) {
  306. return name
  307. }
  308. }
  309. media := "xl/media/image" + strconv.Itoa(count+1) + ext
  310. f.XLSX[media] = file
  311. return media
  312. }
  313. // setContentTypePartImageExtensions provides a function to set the content
  314. // type for relationship parts and the Main Document part.
  315. func (f *File) setContentTypePartImageExtensions() {
  316. var imageTypes = map[string]bool{"jpeg": false, "png": false, "gif": false, "tiff": false}
  317. content := f.contentTypesReader()
  318. for _, v := range content.Defaults {
  319. _, ok := imageTypes[v.Extension]
  320. if ok {
  321. imageTypes[v.Extension] = true
  322. }
  323. }
  324. for k, v := range imageTypes {
  325. if !v {
  326. content.Defaults = append(content.Defaults, xlsxDefault{
  327. Extension: k,
  328. ContentType: "image/" + k,
  329. })
  330. }
  331. }
  332. }
  333. // setContentTypePartVMLExtensions provides a function to set the content type
  334. // for relationship parts and the Main Document part.
  335. func (f *File) setContentTypePartVMLExtensions() {
  336. vml := false
  337. content := f.contentTypesReader()
  338. for _, v := range content.Defaults {
  339. if v.Extension == "vml" {
  340. vml = true
  341. }
  342. }
  343. if !vml {
  344. content.Defaults = append(content.Defaults, xlsxDefault{
  345. Extension: "vml",
  346. ContentType: ContentTypeVML,
  347. })
  348. }
  349. }
  350. // addContentTypePart provides a function to add content type part
  351. // relationships in the file [Content_Types].xml by given index.
  352. func (f *File) addContentTypePart(index int, contentType string) {
  353. setContentType := map[string]func(){
  354. "comments": f.setContentTypePartVMLExtensions,
  355. "drawings": f.setContentTypePartImageExtensions,
  356. }
  357. partNames := map[string]string{
  358. "chart": "/xl/charts/chart" + strconv.Itoa(index) + ".xml",
  359. "chartsheet": "/xl/chartsheets/sheet" + strconv.Itoa(index) + ".xml",
  360. "comments": "/xl/comments" + strconv.Itoa(index) + ".xml",
  361. "drawings": "/xl/drawings/drawing" + strconv.Itoa(index) + ".xml",
  362. "table": "/xl/tables/table" + strconv.Itoa(index) + ".xml",
  363. "pivotTable": "/xl/pivotTables/pivotTable" + strconv.Itoa(index) + ".xml",
  364. "pivotCache": "/xl/pivotCache/pivotCacheDefinition" + strconv.Itoa(index) + ".xml",
  365. "sharedStrings": "/xl/sharedStrings.xml",
  366. }
  367. contentTypes := map[string]string{
  368. "chart": ContentTypeDrawingML,
  369. "chartsheet": ContentTypeSpreadSheetMLChartsheet,
  370. "comments": ContentTypeSpreadSheetMLComments,
  371. "drawings": ContentTypeDrawing,
  372. "table": ContentTypeSpreadSheetMLTable,
  373. "pivotTable": ContentTypeSpreadSheetMLPivotTable,
  374. "pivotCache": ContentTypeSpreadSheetMLPivotCacheDefinition,
  375. "sharedStrings": ContentTypeSpreadSheetMLSharedStrings,
  376. }
  377. s, ok := setContentType[contentType]
  378. if ok {
  379. s()
  380. }
  381. content := f.contentTypesReader()
  382. for _, v := range content.Overrides {
  383. if v.PartName == partNames[contentType] {
  384. return
  385. }
  386. }
  387. content.Overrides = append(content.Overrides, xlsxOverride{
  388. PartName: partNames[contentType],
  389. ContentType: contentTypes[contentType],
  390. })
  391. }
  392. // getSheetRelationshipsTargetByID provides a function to get Target attribute
  393. // value in xl/worksheets/_rels/sheet%d.xml.rels by given worksheet name and
  394. // relationship index.
  395. func (f *File) getSheetRelationshipsTargetByID(sheet, rID string) string {
  396. name, ok := f.sheetMap[trimSheetName(sheet)]
  397. if !ok {
  398. name = strings.ToLower(sheet) + ".xml"
  399. }
  400. var rels = "xl/worksheets/_rels/" + strings.TrimPrefix(name, "xl/worksheets/") + ".rels"
  401. sheetRels := f.relsReader(rels)
  402. if sheetRels == nil {
  403. sheetRels = &xlsxRelationships{}
  404. }
  405. for _, v := range sheetRels.Relationships {
  406. if v.ID == rID {
  407. return v.Target
  408. }
  409. }
  410. return ""
  411. }
  412. // GetPicture provides a function to get picture base name and raw content
  413. // embed in XLSX by given worksheet and cell name. This function returns the
  414. // file name in XLSX and file contents as []byte data types. For example:
  415. //
  416. // f, err := excelize.OpenFile("Book1.xlsx")
  417. // if err != nil {
  418. // fmt.Println(err)
  419. // return
  420. // }
  421. // file, raw, err := f.GetPicture("Sheet1", "A2")
  422. // if err != nil {
  423. // fmt.Println(err)
  424. // return
  425. // }
  426. // if err := ioutil.WriteFile(file, raw, 0644); err != nil {
  427. // fmt.Println(err)
  428. // }
  429. //
  430. func (f *File) GetPicture(sheet, cell string) (string, []byte, error) {
  431. col, row, err := CellNameToCoordinates(cell)
  432. if err != nil {
  433. return "", nil, err
  434. }
  435. col--
  436. row--
  437. xlsx, err := f.workSheetReader(sheet)
  438. if err != nil {
  439. return "", nil, err
  440. }
  441. if xlsx.Drawing == nil {
  442. return "", nil, err
  443. }
  444. target := f.getSheetRelationshipsTargetByID(sheet, xlsx.Drawing.RID)
  445. drawingXML := strings.Replace(target, "..", "xl", -1)
  446. _, ok := f.XLSX[drawingXML]
  447. if !ok {
  448. return "", nil, err
  449. }
  450. drawingRelationships := strings.Replace(
  451. strings.Replace(target, "../drawings", "xl/drawings/_rels", -1), ".xml", ".xml.rels", -1)
  452. return f.getPicture(row, col, drawingXML, drawingRelationships)
  453. }
  454. // DeletePicture provides a function to delete charts in XLSX by given
  455. // worksheet and cell name. Note that the image file won't be deleted from the
  456. // document currently.
  457. func (f *File) DeletePicture(sheet, cell string) (err error) {
  458. col, row, err := CellNameToCoordinates(cell)
  459. if err != nil {
  460. return
  461. }
  462. col--
  463. row--
  464. ws, err := f.workSheetReader(sheet)
  465. if err != nil {
  466. return
  467. }
  468. if ws.Drawing == nil {
  469. return
  470. }
  471. drawingXML := strings.Replace(f.getSheetRelationshipsTargetByID(sheet, ws.Drawing.RID), "..", "xl", -1)
  472. return f.deleteDrawing(col, row, drawingXML, "Pic")
  473. }
  474. // getPicture provides a function to get picture base name and raw content
  475. // embed in XLSX by given coordinates and drawing relationships.
  476. func (f *File) getPicture(row, col int, drawingXML, drawingRelationships string) (ret string, buf []byte, err error) {
  477. var (
  478. wsDr *xlsxWsDr
  479. ok bool
  480. deWsDr *decodeWsDr
  481. drawRel *xlsxRelationship
  482. deTwoCellAnchor *decodeTwoCellAnchor
  483. )
  484. wsDr, _ = f.drawingParser(drawingXML)
  485. if ret, buf = f.getPictureFromWsDr(row, col, drawingRelationships, wsDr); len(buf) > 0 {
  486. return
  487. }
  488. deWsDr = new(decodeWsDr)
  489. if err = f.xmlNewDecoder(bytes.NewReader(namespaceStrictToTransitional(f.readXML(drawingXML)))).
  490. Decode(deWsDr); err != nil && err != io.EOF {
  491. err = fmt.Errorf("xml decode error: %s", err)
  492. return
  493. }
  494. err = nil
  495. for _, anchor := range deWsDr.TwoCellAnchor {
  496. deTwoCellAnchor = new(decodeTwoCellAnchor)
  497. if err = f.xmlNewDecoder(strings.NewReader("<decodeTwoCellAnchor>" + anchor.Content + "</decodeTwoCellAnchor>")).
  498. Decode(deTwoCellAnchor); err != nil && err != io.EOF {
  499. err = fmt.Errorf("xml decode error: %s", err)
  500. return
  501. }
  502. if err = nil; deTwoCellAnchor.From != nil && deTwoCellAnchor.Pic != nil {
  503. if deTwoCellAnchor.From.Col == col && deTwoCellAnchor.From.Row == row {
  504. drawRel = f.getDrawingRelationships(drawingRelationships, deTwoCellAnchor.Pic.BlipFill.Blip.Embed)
  505. if _, ok = supportImageTypes[filepath.Ext(drawRel.Target)]; ok {
  506. ret, buf = filepath.Base(drawRel.Target), f.XLSX[strings.Replace(drawRel.Target, "..", "xl", -1)]
  507. return
  508. }
  509. }
  510. }
  511. }
  512. return
  513. }
  514. // getPictureFromWsDr provides a function to get picture base name and raw
  515. // content in worksheet drawing by given coordinates and drawing
  516. // relationships.
  517. func (f *File) getPictureFromWsDr(row, col int, drawingRelationships string, wsDr *xlsxWsDr) (ret string, buf []byte) {
  518. var (
  519. ok bool
  520. anchor *xdrCellAnchor
  521. drawRel *xlsxRelationship
  522. )
  523. for _, anchor = range wsDr.TwoCellAnchor {
  524. if anchor.From != nil && anchor.Pic != nil {
  525. if anchor.From.Col == col && anchor.From.Row == row {
  526. drawRel = f.getDrawingRelationships(drawingRelationships,
  527. anchor.Pic.BlipFill.Blip.Embed)
  528. if _, ok = supportImageTypes[filepath.Ext(drawRel.Target)]; ok {
  529. ret, buf = filepath.Base(drawRel.Target), f.XLSX[strings.Replace(drawRel.Target, "..", "xl", -1)]
  530. return
  531. }
  532. }
  533. }
  534. }
  535. return
  536. }
  537. // getDrawingRelationships provides a function to get drawing relationships
  538. // from xl/drawings/_rels/drawing%s.xml.rels by given file name and
  539. // relationship ID.
  540. func (f *File) getDrawingRelationships(rels, rID string) *xlsxRelationship {
  541. if drawingRels := f.relsReader(rels); drawingRels != nil {
  542. for _, v := range drawingRels.Relationships {
  543. if v.ID == rID {
  544. return &v
  545. }
  546. }
  547. }
  548. return nil
  549. }
  550. // drawingsWriter provides a function to save xl/drawings/drawing%d.xml after
  551. // serialize structure.
  552. func (f *File) drawingsWriter() {
  553. for path, d := range f.Drawings {
  554. if d != nil {
  555. v, _ := xml.Marshal(d)
  556. f.saveFileList(path, v)
  557. }
  558. }
  559. }
  560. // drawingResize calculate the height and width after resizing.
  561. func (f *File) drawingResize(sheet string, cell string, width, height float64, formatSet *formatPicture) (w, h, c, r int, err error) {
  562. var mergeCells []MergeCell
  563. mergeCells, err = f.GetMergeCells(sheet)
  564. if err != nil {
  565. return
  566. }
  567. var rng []int
  568. var inMergeCell bool
  569. if c, r, err = CellNameToCoordinates(cell); err != nil {
  570. return
  571. }
  572. cellWidth, cellHeight := f.getColWidth(sheet, c), f.getRowHeight(sheet, r)
  573. for _, mergeCell := range mergeCells {
  574. if inMergeCell, err = f.checkCellInArea(cell, mergeCell[0]); err != nil {
  575. return
  576. }
  577. if inMergeCell {
  578. rng, _ = areaRangeToCoordinates(mergeCell.GetStartAxis(), mergeCell.GetEndAxis())
  579. sortCoordinates(rng)
  580. }
  581. }
  582. if inMergeCell {
  583. c, r = rng[0], rng[1]
  584. for col := rng[0] - 1; col < rng[2]; col++ {
  585. cellWidth += f.getColWidth(sheet, col)
  586. }
  587. for row := rng[1] - 1; row < rng[3]; row++ {
  588. cellHeight += f.getRowHeight(sheet, row)
  589. }
  590. }
  591. if float64(cellWidth) < width {
  592. asp := float64(cellWidth) / width
  593. width, height = float64(cellWidth), height*asp
  594. }
  595. if float64(cellHeight) < height {
  596. asp := float64(cellHeight) / height
  597. height, width = float64(cellHeight), width*asp
  598. }
  599. width, height = width-float64(formatSet.OffsetX), height-float64(formatSet.OffsetY)
  600. w, h = int(width*formatSet.XScale), int(height*formatSet.YScale)
  601. return
  602. }