picture.go 20 KB

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