├── .gitignore ├── CHANGELOG.md ├── LICENSE ├── README.md ├── cmd └── gim │ └── gim.go ├── filter-black-white.go ├── filter-sepia.go ├── filter-vignette.go ├── go.mod ├── grid.go ├── image-filter-type.go ├── image-filter.go └── image-merge.go /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | .idea 3 | cmd/gim/output 4 | cmd/gim/input 5 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | ## v0.3.1 - 2024-05-22 2 | - Make the library importable, remove internal folder 3 | 4 | ## v0.3.0 - 2024-04-07 5 | - Added filter support 6 | - fixed ReadImageFile func memory leak by @blue14753 in https://github.com/ozankasikci/go-image-merge/pull/2 7 | - Pass in images by @marcsantiago in https://github.com/ozankasikci/go-image-merge/pull/5 8 | - Grid: Image field is now image.Image by @gucio321 in https://github.com/ozankasikci/go-image-merge/pull/9 9 | 10 | ## v0.2.2 - 2019-12-01 11 | ### Bug Fixes 12 | - Check images before trying to merge 13 | 14 | ## v0.2.1 - 2019-11-29 15 | ### Features 16 | - Export readImageFile method 17 | 18 | ## v0.2.0 - 2019-09-29 19 | 20 | ### Breaking Changes 21 | - gim.New won't accept a []string argument anymore, instead it now expects a []*Grid slice as first argument. 22 | 23 | ### Features 24 | - Add Background color support 25 | - Add Grid Layered drawing support 26 | 27 | ## v0.1.0 - 2019-09-28 28 | 29 | ### Features 30 | - Initial version 31 | - Vertical & Horizontal grid unit count option 32 | - Functional option BaseDir 33 | - Functional option GridSize 34 | - Functional option GridSizeFromNthImage 35 | 36 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## gim - Grid Based Image Merge Library 2 | 3 | `gim` is a image merging library that can accept image paths as input, read the image contents, add background color, draw layers on top of each other, merge them into a grid with the desired size. 4 | 5 | [![Go Report Card](https://goreportcard.com/badge/github.com/ozankasikci/go-image-merge)](https://goreportcard.com/report/github.com/ozankasikci/go-image-merge) 6 | [![GoDoc](https://godoc.org/github.com/ozankasikci/go-image-merge?status.svg)](https://godoc.org/github.com/ozankasikci/go-image-merge) 7 | 8 | ## Table of Contents 9 | 10 | - [Overview](#overview) 11 | - [Installation](#installation) 12 | - [Getting Started](#getting-started) 13 | - [Examples](#examples) 14 | * [Grid Unit Count - Vertical & Horizontal](#grid-unit-count---vertical--horizontal) 15 | * [Grid Background Color](#grid-background-color) 16 | * [Grid Layers - Draw Grids on top of Grids](#grid-layers---draw-grids-on-top-of-grids) 17 | * [Filters](#filters) 18 | - [Functional Options](#functional-options) 19 | - [TODO](#todo) 20 | 21 | ## Overview 22 | 23 | `gim` provides an easy and extensible way to merge images into a flexible grid system. 24 | 25 | The main purpose of the library is to help creating image collages programmatically. 26 | 27 | ## Installation 28 | 29 | `go get -u github.com/ozankasikci/go-image-merge` 30 | 31 | ## Getting Started 32 | 33 | Import the library and give the image paths and grid size as the minimum required arguments. 34 | 35 | Basic usage: 36 | 37 | ```go 38 | import gim "github.com/ozankasikci/go-image-merge" 39 | 40 | // accepts *Grid instances, grid unit count x, grid unit count y 41 | // returns an *image.RGBA object 42 | grids := []*gim.Grid{ 43 | {ImageFilePath: "file.jpg"}, 44 | {ImageFilePath: "file.png"}, 45 | } 46 | rgba, err := gim.New(grids, 2, 1).Merge() 47 | 48 | // save the output to jpg or png 49 | file, err := os.Create("file/path.jpg|png") 50 | err = jpeg.Encode(file, rgba, &jpeg.Options{Quality: 80}) 51 | err = png.Encode(file, rgba) 52 | ``` 53 | 54 | See [Examples](#examples) for available options and advanced usage. 55 | 56 | ## Examples 57 | 58 | ### Grid Unit Count - Vertical & Horizontal 59 | ```go 60 | grids := []*gim.Grid{ 61 | {ImageFilePath: "./cmd/gim/input/kitten.jpg"}, 62 | {ImageFilePath: "./cmd/gim/input/kitten.jpg"}, 63 | {ImageFilePath: "./cmd/gim/input/kitten.jpg"}, 64 | {ImageFilePath: "./cmd/gim/input/kitten.jpg"}, 65 | } 66 | rgba, err := gim.New(grids, 2, 2).Merge() 67 | ``` 68 | 69 | #### Output: 70 | ![](https://raw.githubusercontent.com/ozankasikci/ozankasikci.github.io/master/gim/grid-size-2-2.jpg) 71 | 72 | ### Grid Background Color 73 | ```go 74 | grids := []*gim.Grid{ 75 | { 76 | ImageFilePath: "./cmd/gim/input/ginger.png", 77 | BackgroundColor: color.White, 78 | }, 79 | { 80 | ImageFilePath: "./cmd/gim/input/ginger.png", 81 | BackgroundColor: color.RGBA{R: 0x8b, G: 0xd0, B: 0xc6}, 82 | }, 83 | } 84 | rgba, err := gim.New(grids, 2, 1).Merge() 85 | ``` 86 | 87 | #### Output: 88 | ![](https://raw.githubusercontent.com/ozankasikci/ozankasikci.github.io/master/gim/grid-bg-color.jpg) 89 | 90 | ### Grid Layers - Draw Grids on top of Grids 91 | ```go 92 | grids := []*gim.Grid{ 93 | { 94 | ImageFilePath: "./cmd/gim/input/ginger.png", 95 | BackgroundColor: color.White, 96 | // these grids will be drawn on top of the first grid 97 | Grids: []*gim.Grid{ 98 | { 99 | ImageFilePath: "./cmd/gim/input/tick.png", 100 | OffsetX: 50, OffsetY: 20, 101 | }, 102 | }, 103 | }, 104 | { 105 | ImageFilePath: "./cmd/gim/input/ginger.png", 106 | BackgroundColor: color.RGBA{R: 0x8b, G: 0xd0, B: 0xc6}, 107 | // these grids will be drawn on top of the second grid 108 | Grids: []*gim.Grid{ 109 | { 110 | ImageFilePath: "./cmd/gim/input/tick.png", 111 | OffsetX: 200, OffsetY: 170, 112 | }, 113 | { 114 | ImageFilePath: "./cmd/gim/input/tick.png", 115 | OffsetX: 200, OffsetY: 20, 116 | }, 117 | }, 118 | }, 119 | } 120 | rgba, err := gim.New(grids, 2, 1).Merge() 121 | ``` 122 | 123 | #### Output: 124 | ![](https://raw.githubusercontent.com/ozankasikci/ozankasikci.github.io/master/gim/grid-layers.jpg) 125 | 126 | ## Filters 127 | 128 | ### Available Filters 129 | 130 | - **Black & White**: Converts an image to grayscale. 131 | - **Sepia**: Applies a sepia filter to an image. 132 | - **Vignette**: Applies a vignette filter to an image. 133 | 134 | ### Applying Filters 135 | 136 | To apply filters, include them in the `Filters` slice of the `Grid` struct. Each `Grid` can have multiple filters applied, which will be processed in the order they are added. 137 | 138 | ### Example: Black & White Filter 139 | 140 | 141 | ```go 142 | grids := []*gim.Grid{ 143 | { 144 | ImageFilePath: "./cmd/gim/input/ginger2.png", 145 | Filters: []imagefilter.FilterType{ 146 | imagefilter.BlackAndWhite, 147 | }, 148 | }, 149 | { 150 | ImageFilePath: "./cmd/gim/input/ginger2.png", 151 | }, 152 | } 153 | ``` 154 | #### Output: 155 | ![](https://raw.githubusercontent.com/ozankasikci/ozankasikci.github.io/master/gim/black-white-filter.jpg) 156 | 157 | ## Functional Options 158 | 159 | ### OptBaseDir 160 | ```go 161 | // you can omit the full path if you set a base dir 162 | grids := []*gim.Grid{ 163 | {ImageFilePath: "kitten.jpg"}, 164 | {ImageFilePath: "kitten.jpg"}, 165 | } 166 | rgba, err := gim.New( 167 | grids, 1, 2, 168 | gim.OptBaseDir("./cmd/gim/input"), 169 | ).Merge() 170 | ``` 171 | 172 | ### OptGridSize 173 | ```go 174 | // you can resize the grids in pixels 175 | grids := []*gim.Grid{ 176 | {ImageFilePath: "kitten.jpg"}, 177 | {ImageFilePath: "kitten.jpg"}, 178 | } 179 | rgba, err := gim.New( 180 | grids, 2, 1, 181 | gim.OptBaseDir("./cmd/gim"), 182 | gim.OptGridSize(200,150), 183 | ).Merge() 184 | ``` 185 | #### Output: 186 | ![](https://raw.githubusercontent.com/ozankasikci/ozankasikci.github.io/master/gim/grid-resize-pixels-200-150.jpg) 187 | 188 | ## TODO 189 | - [x] Add colored background support 190 | - [ ] Add resize support (stretch, fit etc.) 191 | - [x] Add filters 192 | 193 | -------------------------------------------------------------------------------- /cmd/gim/gim.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | gim "github.com/ozankasikci/go-image-merge" 5 | "image/color" 6 | "image/jpeg" 7 | "log" 8 | "os" 9 | ) 10 | 11 | func main() { 12 | grids := []*gim.Grid{ 13 | { 14 | ImageFilePath: "./cmd/gim/input/ginger.png", 15 | BackgroundColor: color.White, 16 | Filters: []gim.FilterType{ 17 | gim.Vignette, 18 | }, 19 | }, 20 | { 21 | ImageFilePath: "./cmd/gim/input/ginger.png", 22 | BackgroundColor: color.RGBA{R: 0x8b, G: 0xd0, B: 0xc6}, 23 | }, 24 | } 25 | rgba, err := gim.New(grids, 2, 1).Merge() 26 | if err != nil { 27 | log.Panicf(err.Error()) 28 | } 29 | 30 | file, err := os.Create("cmd/gim/output/merged.jpg") 31 | if err != nil { 32 | log.Panicf(err.Error()) 33 | } 34 | 35 | err = jpeg.Encode(file, rgba, &jpeg.Options{Quality: 80}) 36 | if err != nil { 37 | log.Panicf(err.Error()) 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /filter-black-white.go: -------------------------------------------------------------------------------- 1 | package goimagemerge 2 | 3 | import ( 4 | "image" 5 | "image/color" 6 | ) 7 | 8 | func init() { 9 | Register(BlackAndWhite, new(BlackAndWhiteFilter)) 10 | } 11 | 12 | type BlackAndWhiteFilter struct{} 13 | 14 | func (bwf BlackAndWhiteFilter) Apply(img image.Image) image.Image { 15 | bounds := img.Bounds() 16 | grayImg := image.NewGray(bounds) 17 | for y := bounds.Min.Y; y < bounds.Max.Y; y++ { 18 | for x := bounds.Min.X; x < bounds.Max.X; x++ { 19 | originalColor := img.At(x, y) 20 | grayColor := color.GrayModel.Convert(originalColor) 21 | grayImg.Set(x, y, grayColor) 22 | } 23 | } 24 | return grayImg 25 | } 26 | -------------------------------------------------------------------------------- /filter-sepia.go: -------------------------------------------------------------------------------- 1 | package goimagemerge 2 | 3 | import ( 4 | "image" 5 | "image/color" 6 | ) 7 | 8 | func init() { 9 | Register(Sepia, new(SepiaFilter)) 10 | } 11 | 12 | type SepiaFilter struct{} 13 | 14 | func (sf *SepiaFilter) Apply(img image.Image) image.Image { 15 | bounds := img.Bounds() 16 | dst := image.NewRGBA(bounds) 17 | 18 | for y := bounds.Min.Y; y < bounds.Max.Y; y++ { 19 | for x := bounds.Min.X; x < bounds.Max.X; x++ { 20 | originalColor := color.RGBAModel.Convert(img.At(x, y)).(color.RGBA) 21 | r, g, b := originalColor.R, originalColor.G, originalColor.B 22 | 23 | // Calculate sepia tones 24 | newR := (0.393 * float64(r)) + (0.769 * float64(g)) + (0.189 * float64(b)) 25 | newG := (0.349 * float64(r)) + (0.686 * float64(g)) + (0.168 * float64(b)) 26 | newB := (0.272 * float64(r)) + (0.534 * float64(g)) + (0.131 * float64(b)) 27 | 28 | // Clamp values 29 | newR = min(newR, 255) 30 | newG = min(newG, 255) 31 | newB = min(newB, 255) 32 | 33 | // Mix with original color to reduce intensity 34 | mixFactor := 0.7 // Adjust this value to control the sepia intensity 35 | mixedR := mixFactor*newR + (1-mixFactor)*float64(r) 36 | mixedG := mixFactor*newG + (1-mixFactor)*float64(g) 37 | mixedB := mixFactor*newB + (1-mixFactor)*float64(b) 38 | 39 | dst.Set(x, y, color.RGBA{ 40 | R: uint8(mixedR), 41 | G: uint8(mixedG), 42 | B: uint8(mixedB), 43 | A: originalColor.A, 44 | }) 45 | } 46 | } 47 | return dst 48 | } 49 | 50 | // min returns the smaller of x or y. 51 | func min(x, y float64) float64 { 52 | if x < y { 53 | return x 54 | } 55 | return y 56 | } 57 | -------------------------------------------------------------------------------- /filter-vignette.go: -------------------------------------------------------------------------------- 1 | package goimagemerge 2 | 3 | import ( 4 | "image" 5 | "image/color" 6 | "math" 7 | ) 8 | 9 | func init() { 10 | Register(Vignette, new(VignetteFilter)) 11 | } 12 | 13 | type VignetteFilter struct{} 14 | 15 | func (vf *VignetteFilter) Apply(img image.Image) image.Image { 16 | bounds := img.Bounds() 17 | dst := image.NewRGBA(bounds) 18 | centerX, centerY := float64(bounds.Dx())/2, float64(bounds.Dy())/2 19 | maxDistance := math.Sqrt(centerX*centerX + centerY*centerY) 20 | 21 | for y := bounds.Min.Y; y < bounds.Max.Y; y++ { 22 | for x := bounds.Min.X; x < bounds.Max.X; x++ { 23 | originalColor := img.At(x, y) 24 | distToCenter := math.Sqrt(math.Pow(float64(x)-centerX, 2) + math.Pow(float64(y)-centerY, 2)) 25 | factor := distToCenter / maxDistance 26 | 27 | // Adjusting the curve for a stronger darkening effect towards the edges 28 | factor = 1 - (factor * factor * 0.95) // Increase the multiplier for a stronger effect 29 | 30 | // Ensure the factor does not make the image too dark, adjust the minimum threshold as needed 31 | if factor < 0.15 { 32 | factor = 0.15 // Lowering the threshold allows for more darkening at the edges 33 | } 34 | 35 | r, g, b, a := originalColor.RGBA() 36 | dst.Set(x, y, color.RGBA{ 37 | R: uint8(float64(r>>8) * factor), 38 | G: uint8(float64(g>>8) * factor), 39 | B: uint8(float64(b>>8) * factor), 40 | A: uint8(a >> 8), 41 | }) 42 | } 43 | } 44 | return dst 45 | } 46 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/ozankasikci/go-image-merge 2 | 3 | go 1.13 4 | -------------------------------------------------------------------------------- /grid.go: -------------------------------------------------------------------------------- 1 | package goimagemerge 2 | 3 | import ( 4 | "image" 5 | "image/color" 6 | ) 7 | 8 | // Grid holds the data for each grid 9 | type Grid struct { 10 | Image image.Image 11 | ImageFilePath string 12 | BackgroundColor color.Color 13 | OffsetX int 14 | OffsetY int 15 | Grids []*Grid 16 | Filters []FilterType 17 | } 18 | 19 | // ApplyFilters applies the selected filters to the image. 20 | func (g Grid) ApplyFilters(img image.Image) image.Image { 21 | for _, filterType := range g.Filters { 22 | filter := GetFilter(filterType) 23 | if filter != nil { 24 | img = filter.Apply(img) 25 | } 26 | } 27 | 28 | return img 29 | } 30 | -------------------------------------------------------------------------------- /image-filter-type.go: -------------------------------------------------------------------------------- 1 | package goimagemerge 2 | 3 | // FilterType defines the type of filter to apply to the image. 4 | type FilterType int 5 | 6 | const ( 7 | NoFilter FilterType = iota 8 | // BlackAndWhite applies a black and white filter. 9 | BlackAndWhite 10 | Vignette 11 | Sepia 12 | ) 13 | -------------------------------------------------------------------------------- /image-filter.go: -------------------------------------------------------------------------------- 1 | package goimagemerge 2 | 3 | import "image" 4 | 5 | // Filter is the interface that wraps the Apply method. 6 | type Filter interface { 7 | Apply(image.Image) image.Image 8 | } 9 | 10 | var Filters = make(map[FilterType]Filter) 11 | 12 | func Register(filterType FilterType, filter Filter) { 13 | Filters[filterType] = filter 14 | } 15 | 16 | func GetFilter(filterType FilterType) Filter { 17 | return Filters[filterType] 18 | } 19 | -------------------------------------------------------------------------------- /image-merge.go: -------------------------------------------------------------------------------- 1 | package goimagemerge 2 | 3 | import ( 4 | "errors" 5 | "image" 6 | "image/draw" 7 | "image/jpeg" 8 | "image/png" 9 | "os" 10 | "path" 11 | "path/filepath" 12 | "strings" 13 | ) 14 | 15 | // Specifies how the grid pixel size should be calculated 16 | type gridSizeMode int 17 | 18 | const ( 19 | // The size in pixels is fixed for all the grids 20 | fixedGridSize gridSizeMode = iota 21 | // The size in pixels is set to the nth image size 22 | gridSizeFromImage 23 | ) 24 | 25 | // MergeImage is the struct that is responsible for merging the given images 26 | type MergeImage struct { 27 | Grids []*Grid 28 | ImageCountDX int 29 | ImageCountDY int 30 | BaseDir string 31 | FixedGridSizeX int 32 | FixedGridSizeY int 33 | GridSizeMode gridSizeMode 34 | GridSizeFromNth int 35 | } 36 | 37 | // New returns a new *MergeImage instance 38 | func New(grids []*Grid, imageCountDX, imageCountDY int, opts ...func(*MergeImage)) *MergeImage { 39 | mi := &MergeImage{ 40 | Grids: grids, 41 | ImageCountDX: imageCountDX, 42 | ImageCountDY: imageCountDY, 43 | } 44 | 45 | for _, option := range opts { 46 | option(mi) 47 | } 48 | 49 | return mi 50 | } 51 | 52 | // OptBaseDir is an functional option to set the BaseDir field 53 | func OptBaseDir(dir string) func(*MergeImage) { 54 | return func(mi *MergeImage) { 55 | mi.BaseDir = dir 56 | } 57 | } 58 | 59 | // OptGridSize is an functional option to set the GridSize X & Y 60 | func OptGridSize(sizeX, sizeY int) func(*MergeImage) { 61 | return func(mi *MergeImage) { 62 | mi.GridSizeMode = fixedGridSize 63 | mi.FixedGridSizeX = sizeX 64 | mi.FixedGridSizeY = sizeY 65 | } 66 | } 67 | 68 | // OptGridSizeFromNthImageSize is an functional option to set the GridSize from the nth image 69 | func OptGridSizeFromNthImageSize(n int) func(*MergeImage) { 70 | return func(mi *MergeImage) { 71 | mi.GridSizeMode = gridSizeFromImage 72 | mi.GridSizeFromNth = n 73 | } 74 | } 75 | 76 | func (m *MergeImage) readGridImage(grid *Grid) (image.Image, error) { 77 | if grid.Image != nil { 78 | return grid.ApplyFilters(grid.Image), nil 79 | } 80 | 81 | imgPath := grid.ImageFilePath 82 | 83 | if m.BaseDir != "" { 84 | imgPath = path.Join(m.BaseDir, grid.ImageFilePath) 85 | } 86 | 87 | img, err := m.ReadImageFile(imgPath) 88 | if err != nil { 89 | return nil, err 90 | } 91 | 92 | return grid.ApplyFilters(img), nil 93 | } 94 | 95 | func (m *MergeImage) readGridsImages() ([]image.Image, error) { 96 | var images []image.Image 97 | 98 | for _, grid := range m.Grids { 99 | img, err := m.readGridImage(grid) 100 | if err != nil { 101 | return nil, err 102 | } 103 | 104 | images = append(images, img) 105 | } 106 | 107 | return images, nil 108 | } 109 | 110 | func (m *MergeImage) ReadImageFile(path string) (image.Image, error) { 111 | absPath, err := filepath.Abs(path) 112 | if err != nil { 113 | return nil, err 114 | } 115 | 116 | imgFile, err := os.Open(absPath) 117 | if err != nil { 118 | return nil, err 119 | } 120 | defer imgFile.Close() 121 | 122 | var img image.Image 123 | splittedPath := strings.Split(path, ".") 124 | ext := splittedPath[len(splittedPath)-1] 125 | 126 | if ext == "jpg" || ext == "jpeg" { 127 | img, err = jpeg.Decode(imgFile) 128 | } else { 129 | img, err = png.Decode(imgFile) 130 | } 131 | 132 | if err != nil { 133 | return nil, err 134 | } 135 | 136 | return img, nil 137 | } 138 | 139 | func (m *MergeImage) mergeGrids(images []image.Image) (*image.RGBA, error) { 140 | var canvas *image.RGBA 141 | imageBoundX := 0 142 | imageBoundY := 0 143 | 144 | if m.GridSizeMode == fixedGridSize && m.FixedGridSizeX != 0 && m.FixedGridSizeY != 0 { 145 | imageBoundX = m.FixedGridSizeX 146 | imageBoundY = m.FixedGridSizeY 147 | } else if m.GridSizeMode == gridSizeFromImage { 148 | imageBoundX = images[m.GridSizeFromNth].Bounds().Dx() 149 | imageBoundY = images[m.GridSizeFromNth].Bounds().Dy() 150 | } else { 151 | imageBoundX = images[0].Bounds().Dx() 152 | imageBoundY = images[0].Bounds().Dy() 153 | } 154 | 155 | canvasBoundX := m.ImageCountDX * imageBoundX 156 | canvasBoundY := m.ImageCountDY * imageBoundY 157 | 158 | canvasMaxPoint := image.Point{canvasBoundX, canvasBoundY} 159 | canvasRect := image.Rectangle{image.Point{0, 0}, canvasMaxPoint} 160 | canvas = image.NewRGBA(canvasRect) 161 | 162 | // draw grids one by one 163 | for i, grid := range m.Grids { 164 | img := images[i] 165 | x := i % m.ImageCountDX 166 | y := i / m.ImageCountDX 167 | minPoint := image.Point{x * imageBoundX, y * imageBoundY} 168 | maxPoint := minPoint.Add(image.Point{imageBoundX, imageBoundY}) 169 | nextGridRect := image.Rectangle{minPoint, maxPoint} 170 | 171 | if grid.BackgroundColor != nil { 172 | draw.Draw(canvas, nextGridRect, &image.Uniform{grid.BackgroundColor}, image.Point{}, draw.Src) 173 | draw.Draw(canvas, nextGridRect, img, image.Point{}, draw.Over) 174 | } else { 175 | draw.Draw(canvas, nextGridRect, img, image.Point{}, draw.Src) 176 | } 177 | 178 | if grid.Grids == nil { 179 | continue 180 | } 181 | 182 | // draw top layer grids 183 | for _, grid := range grid.Grids { 184 | img, err := m.readGridImage(grid) 185 | if err != nil { 186 | return nil, err 187 | } 188 | 189 | gridRect := nextGridRect.Bounds().Add(image.Point{grid.OffsetX, grid.OffsetY}) 190 | draw.Draw(canvas, gridRect, img, image.Point{}, draw.Over) 191 | } 192 | } 193 | 194 | return canvas, nil 195 | } 196 | 197 | // Merge reads the contents of the given file paths, merges them according to given configuration 198 | func (m *MergeImage) Merge() (*image.RGBA, error) { 199 | images, err := m.readGridsImages() 200 | if err != nil { 201 | return nil, err 202 | } 203 | 204 | if len(images) == 0 { 205 | return nil, errors.New("There is no image to merge") 206 | } 207 | 208 | return m.mergeGrids(images) 209 | } 210 | --------------------------------------------------------------------------------