Home >Backend Development >Golang >Read multi-page tiff and extract images in golang

Read multi-page tiff and extract images in golang

PHPz
PHPzforward
2024-02-06 11:24:09611browse

在 golang 中读取多页 tiff 并提取图像

Question content

How to split multi-page tiff into images in Go? DecodeAll of image/tiff returns a TIFF containing image.image. But don't know how to convert each to image?


Correct answer


Since there isn't much information about the package you used in your question, I'm assuming you used github.com/chai2010/tiff Modules. It only contains the decodeall method. I used public multi-page tiff. Then I used the code from package Documentation. Anyway, I'm quoting it here

package main

import (
    "bytes"
    "fmt"
    "io/ioutil"
    "log"
    "path/filepath"

    "github.com/chai2010/tiff"
)

func main() {
    b, err := ioutil.ReadFile("Multi_page24bpp.tif")
    if err != nil {
        panic(err)
    }

    // Decode tiff
    m, errors, err := tiff.DecodeAll(bytes.NewReader(b))
    if err != nil {
        log.Println(err)
    }

    // Encode tiff
    for i := 0; i < len(m); i++ {
        for j := 0; j < len(m[i]); j++ {
            newname := fmt.Sprintf("%s-%02d-%02d.tif", filepath.Base("Multi_page24bpp.tif"), i, j)
            if errors[i][j] != nil {
                log.Printf("%s: %v\n", newname, err)
                continue
            }

            var buf bytes.Buffer
            if err = tiff.Encode(&buf, m[i][j], nil); err != nil {
                log.Fatal(err)
            }
            if err = ioutil.WriteFile(newname, buf.Bytes(), 0666); err != nil {
                log.Fatal(err)
            }
            fmt.Printf("Save %s ok\n", newname)
        }
    }
}

It creates multiple tif images as per your requirement. I hope this is what you meant

The above is the detailed content of Read multi-page tiff and extract images in golang. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete