picture.go 20 KB

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