示例#1
0
func procImage(fileName string) (string, error) {
	reader, err := os.Open(fileName)
	if err != nil {
		fmt.Errorf("Failed to open image with error: %s\n", err)
		return "", err
	}
	defer reader.Close()

	src, _, err := image.Decode(reader)
	if err != nil {
		fmt.Errorf("Failed to decode image with error: %s\n", err)
		return "", err
	}

	g := gift.New(
		gift.Invert(),
	)

	dst := image.NewRGBA(g.Bounds(src.Bounds()))
	g.Draw(dst, src)

	var opt jpeg.Options
	opt.Quality = 100

	fileName = fileName + "_processed.jpg"

	out, _ := os.Create(fileName)
	err = jpeg.Encode(out, dst, &opt)
	if err != nil {
		fmt.Errorf("Failed to encode image with error: %s\n", err)
		return "", err
	}

	return fileName, nil
}
示例#2
0
文件: invert.go 项目: faiq/goglitch
func InvertImage(input string, outfile string) {
	reader, err := os.Open(input)
	if err != nil {
		panic(err)
	}
	defer reader.Close()
	img, _, err := image.Decode(reader)
	if err != nil {
		panic(err)
	}
	bounds := img.Bounds()
	inverted := image.NewNRGBA(bounds)
	for y := bounds.Min.Y; y < bounds.Max.Y; y++ {
		for x := bounds.Min.X; x < bounds.Max.X; x++ {
			r, g, b, a := img.At(x, y).RGBA()
			r = 255 - r>>8
			g = 255 - g>>8
			b = 255 - b>>8
			inverted.SetNRGBA(x, y, color.NRGBA{uint8(r), uint8(g), uint8(b), uint8(a)})
		}
	}
	pwd, _ := os.Getwd()
	fileName := path.Join(pwd, outfile)
	fp, err := os.Create(fileName)
	if err != nil {
		panic(err)
	}
	idx := strings.LastIndex(fileName, ".")
	if idx == -1 {
		panic(errors.New("you dont have a supported output file"))
	}
	ext := fileName[idx+1:]
	if ext == "png" {
		err = png.Encode(fp, inverted)
		if err != nil {
			panic(err)
		}
	} else if ext == "jpeg" || ext == "jpg" {
		var opt jpeg.Options
		opt.Quality = 100
		err = jpeg.Encode(fp, inverted, &opt)
		if err != nil {
			panic(err)
		}
	} else if ext == "gif" {
		var opt gif.Options
		opt.NumColors = 256
		err = gif.Encode(fp, inverted, &opt)
	} else {
		panic(errors.New("you dont have a supported output file"))
	}
}
示例#3
0
文件: resize.go 项目: brydavis/resize
func WriteToFile(filename string, img *image.RGBA) error {
	out, _ := os.Create(filename)

	switch ext := path.Ext(filename); ext {
	case ".jpg", ".jpeg":
		var opt jpeg.Options
		opt.Quality = 1000
		jpeg.Encode(out, img, &opt)
	case ".png":
		png.Encode(out, img)
	default:
		return errors.New("Unable to encode image")
	}
	return nil
}
示例#4
0
func writeToJPEG(imageData image.Image) {

	out, osCreateErr := os.Create(outputImage)
	if osCreateErr != nil {
		log.Println("Create File (OS): ", osCreateErr)
	}
	defer out.Close()

	var opt jpeg.Options
	opt.Quality = 100

	jpegErr := jpeg.Encode(out, imageData, &opt)
	if jpegErr != nil {
		log.Println("Create File (JPEG Encode): ", jpegErr)
	}
}
示例#5
0
func SameToDisk(context *common.AppContext, imagePath string, imageToSave *image.Image) error {
	if imgFilePng, err := os.Create(imagePath); err != nil {
		context.Log.Printf("Error saving PNG image: %s\n", err)
		return err
	} else {
		defer imgFilePng.Close()
		buffer := bufio.NewWriter(imgFilePng)
		var opt jpeg.Options
		opt.Quality = 95
		err := jpeg.Encode(buffer, *imageToSave, &opt)
		if err != nil {
			context.Log.Printf("Error encoding image:%s", err)
			return err
		}
		buffer.Flush()
		return nil
	}
}
示例#6
0
func main() {
	//image.RegisterFormat(name, magic, decode, decodeConfig)
	file, err := os.Open("E:\\psds18291.jpg")
	if err != nil {
		log.Fatal("open file err:", err)
	}
	defer file.Close()
	img, str, err := image.Decode(file)
	if err != nil {
		log.Fatal("decode image err:", err)
	}
	log.Println(img.Bounds(), str)
	outfilepng, err := os.OpenFile("c:\\test1.jpg", os.O_CREATE|os.O_WRONLY, 0666)
	if err != nil {
		return
	}
	outfilejpg, err := os.OpenFile("c:\\test.jpg", os.O_CREATE|os.O_WRONLY, 0666)
	if err != nil {
		return
	}
	defer outfilejpg.Close()
	defer outfilepng.Close()
	rect := img.Bounds()
	rect = rect.Inset(10)
	m0 := image.NewRGBA(image.Rect(0, 0, 80, 50))
	for i := 0; i < m0.Bounds().Dx(); i++ {
		for j := 0; j < m0.Bounds().Dy(); j++ {
			m0.Set(i, j, color.RGBA{255, 0, 0, 255})
		}
	}
	m1, _ := m0.SubImage(image.Rect(1, 2, 5, 5)).(*image.RGBA)
	fmt.Println(m0.Bounds().Dx(), m1.Bounds().Dx())
	fmt.Println(m0.Stride == m1.Stride)
	m2 := m0.SubImage(image.Rect(0, 0, m0.Bounds().Dx(), m0.Bounds().Dy()))
	fmt.Println(m2.Bounds().Dx(), m2.Bounds().Dy())
	opt := jpeg.Options{Quality: 10}
	jpeg.Encode(outfilejpg, img, &opt)
	//png.Encode(outfilepng, img)
	//png.Encode(outfilepng, m0)
	uniform := image.NewUniform(color.RGBA{255, 255, 0, 0})
	//png.Encode(outfilepng, uniform)
	opt.Quality = 100
	jpeg.Encode(outfilepng, uniform, &opt)
}
示例#7
0
func extractAndProcess(context *common.AppContext, fileNames <-chan string, results chan<- string, errChan chan<- error, directoryName string) {
	for fileName := range fileNames {
		filePath := common.DownloadBasePath + directoryName + "/" + fileName
		imageFile, err := os.Open(filePath)
		if err != nil {
			context.Log.Printf("Unable to open the image file %v Error is %v \n", fileName, err)
			errChan <- err
		}
		img, _, err := image.Decode(imageFile)
		if err != nil {
			context.Log.Println("ERROR: Not able to decode the image file. Error is: ", err)
			errChan <- err
		}

		nrgbaImage := ToNRGBA(img)
		bounds := nrgbaImage.Bounds()
		boundsString := fmt.Sprintln(bounds)
		context.Log.Println("The bounds BEFORE the resize are: ", boundsString)

		nrgbaImage = Resize(context, nrgbaImage, tileSize, tileSize)

		bounds = nrgbaImage.Bounds()
		boundsString = fmt.Sprintln(bounds)
		context.Log.Println("The bounds AFTER the resize are: ", boundsString)

		var opt jpeg.Options

		opt.Quality = 80

		imageFile.Close()
		writeFile, err := os.Create(filePath)
		if err != nil {
			context.Log.Println("Unable to open the file for writing. Error is:", err)
		}
		err = jpeg.Encode(writeFile, nrgbaImage, &opt)
		if err != nil {
			context.Log.Println("ERROR: Not able to write to file with JPEG encoding", err)
			errChan <- err
		}

		results <- boundsString
		writeFile.Close()
	}
}
示例#8
0
func Barcode(data string) (pdf *gofpdf.Fpdf, err error) {
	b, err := code128.Encode(data)
	if err != nil {
		return
	}

	b, err = barcode.Scale(b, b.Bounds().Size().X, 10)
	if err != nil {
		panic(err)
	}

	out, err := ioutil.TempFile("", "lblmgrpnpbarcode")
	if err != nil {
		panic(err)
	}
	var opt jpeg.Options

	opt.Quality = 100
	err = jpeg.Encode(out, b, &opt)
	if err != nil {
		return
	}

	imgHeight := float64(b.Bounds().Size().Y)
	imgWidth := float64(b.Bounds().Size().X / 3)

	pdf = gofpdf.NewCustom(&gofpdf.InitType{
		UnitStr: "mm",
		Size:    gofpdf.SizeType{Wd: imgWidth, Ht: imgHeight},
	})

	pdf.AddPage()

	height, width := pdf.GetPageSize()
	pdf.Image(out.Name(), 0, 0, height, width, false, "jpg", 0, "")

	pdf.SetFillColor(255, 255, 255)
	pdf.Rect(0, 7, imgWidth, 5, "F")
	pdf.SetFont("Arial", "B", 6)
	pdf.Text(0, 9.1, data)
	out.Close()
	os.Remove(out.Name())
	return
}
示例#9
0
func writeImgToFile(img image.Image, filename string) {
	out, err := os.Create(filename)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
	var opt jpeg.Options

	opt.Quality = 100
	// ok, write out the data into the new JPEG file

	err = jpeg.Encode(out, img, &opt) // put quality to 80%
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	fmt.Println("Generated image to " + filename + " \n")
}
示例#10
0
func writeToJP(t int) {

	outFile := fmt.Sprint("/Users/muralib/go/output/output", strconv.Itoa(t), ".jpg")
	if t < 10 {
		outFile = fmt.Sprint("/Users/muralib/go/output/output00", strconv.Itoa(t), ".jpg")
	} else if t < 100 {
		outFile = fmt.Sprint("/Users/muralib/go/output/output0", strconv.Itoa(t), ".jpg")
	}

	out, err := os.Create(outFile)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
	imgRect := image.Rect(0, 0, gridSize*10, gridSize*10)
	img := image.NewGray(imgRect)
	draw.Draw(img, img.Bounds(), &image.Uniform{color.White}, image.ZP, draw.Src)
	for x := 0; x < gridSize; x++ {
		for y := 0; y < gridSize; y++ {
			fill := &image.Uniform{color.White}
			if Env[x][y] == -1 {
				fill = &image.Uniform{color.Black}
			} else if Env[x][y] > 1 {
				c := color.Gray{uint8(Env[x][y] * 20)}
				fill = &image.Uniform{c}
			}

			draw.Draw(img, image.Rect((x-1)*10, (y-1)*10, x*10, y*10), fill, image.ZP, draw.Src)
		}
	}

	var opt jpeg.Options

	opt.Quality = 80
	// ok, write out the data into the new JPEG file
	err = jpeg.Encode(out, img, &opt) // put quality to 80%
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
	fmt.Println("Generated image to output.jpg \n")
}
示例#11
0
func main() {
	flag.Parse()
	rand.Seed(time.Now().UTC().UnixNano())

	for i := 1; i < 10; i++ {
		outFile := fmt.Sprint("/Users/muralib/go/output/output", strconv.Itoa(i), ".jpg")
		out, err := os.Create(outFile)
		if err != nil {
			fmt.Println(err)
			os.Exit(1)
		}

		// generate some QR code look a like image
		c := color.Gray{uint8(128)}
		imgRect := image.Rect(0, 0, 100, 100)
		img := image.NewGray(imgRect)
		draw.Draw(img, img.Bounds(), &image.Uniform{color.White}, image.ZP, draw.Src)
		for y := 0; y < 100; y += 10 {
			for x := 0; x < 100; x += 10 {
				fill := &image.Uniform{c}
				if rand.Intn(10)%2 == 0 {
					fill = &image.Uniform{color.White}
				}
				draw.Draw(img, image.Rect(x, y, x+10, y+10), fill, image.ZP, draw.Src)
			}
		}

		var opt jpeg.Options

		opt.Quality = 80
		// ok, write out the data into the new JPEG file

		err = jpeg.Encode(out, img, &opt) // put quality to 80%
		if err != nil {
			fmt.Println(err)
			os.Exit(1)
		}

		fmt.Println("Generated image to output.jpg \n")
	}
}
示例#12
0
func ConvertToJpeg(filename string) (string, error) {
	pngImageFile, err := os.Open(filename)

	if err != nil {
		return "", err
	}

	defer pngImageFile.Close()

	pngSource, err := png.Decode(pngImageFile)

	if err != nil {
		return "", err
	}

	jpegImage := image.NewRGBA(pngSource.Bounds())

	draw.Draw(jpegImage, jpegImage.Bounds(), &image.Uniform{color.White}, image.Point{}, draw.Src)
	draw.Draw(jpegImage, jpegImage.Bounds(), pngSource, pngSource.Bounds().Min, draw.Over)

	outfile := fmt.Sprintf("%s_jpg", filename)
	jpegImageFile, err := os.Create(outfile)

	if err != nil {
		return "", err
	}

	defer jpegImageFile.Close()

	var options jpeg.Options
	options.Quality = 100

	err = jpeg.Encode(jpegImageFile, jpegImage, &options)

	if err != nil {
		fmt.Printf("JPEG Encoding Error: %v\n", err)
		os.Exit(1)
	}

	return outfile, nil
}
示例#13
0
func WriteImage(img image.Image, ext string, w io.Writer) error {
	var err error
	if ext == "png" {
		err = png.Encode(w, img)
		if err != nil {
			return err
		}
	} else if ext == "jpeg" || ext == "jpg" {
		var opt jpeg.Options
		opt.Quality = 100
		err = jpeg.Encode(w, img, &opt)
		if err != nil {
			return err
		}
	} else if ext == "gif" {
		var opt gif.Options
		opt.NumColors = 256
		err = gif.Encode(w, img, &opt)
	} else {
		return errors.New("you dont have a supported output file")
	}
	return nil
}
示例#14
0
// generate one thumbnail
func generateThumbnail(image_file string, overwrite bool) error {
	var err error
	if IsDirectory(thumbs_path) {
		source_image := folder_path + "/" + image_file

		mime, err := getContentType(source_image)
		if err != nil {
			return err
		}

		for thumb_folder, thumb_size := range thumb_sizes {
			thumb_folder_path := thumbs_path + "/" + thumb_folder
			if !Exists(thumb_folder_path) {
				log.Println("Creating folder" + thumb_folder_path)
				err := os.Mkdir(thumb_folder_path, 0755)
				if err != nil {
					return err
				}
			}

			if IsDirectory(thumb_folder_path) {
				thumb_file_path := thumb_folder_path + "/" + image_file

				width, height, exact_size, err := parseSize(thumb_size)
				if err != nil {
					return err
				}

				if Exists(thumb_file_path) && overwrite == false {
					log.Printf("Nothing to do, thumb %s already exists\n", thumb_file_path)
				} else {
					var img image.Image

					file, err := os.Open(source_image)
					if err != nil {
						return err
					}

					if mime == "image/jpeg" {
						img, err = jpeg.Decode(file)
						if err != nil {
							return err
						}
					} else if mime == "image/gif" {
						img, err = gif.Decode(file)
						if err != nil {
							return err
						}
					} else if mime == "image/png" {
						img, err = png.Decode(file)
						if err != nil {
							return err
						}
					}

					file.Close()

					var resized_image image.Image

					if exact_size {
						img_width, img_height, err := getImageDimensions(source_image)
						if err != nil {
							return err
						}

						img_ratio := float64(img_width) / float64(img_height)

						thumb_ratio := float64(width) / float64(height)

						resize_width := uint(width)
						resize_height := uint(height)

						if img_ratio > thumb_ratio {
							resize_width = uint(img_width * 5)
						} else {
							resize_height = uint(img_height * 5)
						}

						image := resize.Thumbnail(resize_width, resize_height, img, resize.Lanczos3)

						resized_image, err = cutter.Crop(image, cutter.Config{
							Width:  width,
							Height: height,
						})
						if err != nil {
							return err
						}

					} else {
						resized_image = resize.Thumbnail(uint(width), uint(height), img, resize.Lanczos3)
					}

					out, err := os.Create(thumb_file_path)
					if err != nil {
						return err
					}

					defer out.Close()

					if mime == "image/jpeg" {
						var jpeg_opt jpeg.Options
						jpeg_opt.Quality = viper.GetInt("jpeg_quality")
						jpeg.Encode(out, resized_image, &jpeg_opt)
					} else if mime == "image/gif" {
						var gif_opt gif.Options
						gif_opt.NumColors = 256

						gif.Encode(out, resized_image, &gif_opt)
					} else if mime == "image/png" {
						png.Encode(out, resized_image)
					}
				}
			} else {
				return errors.New("Can't create thumbnails. " + thumb_folder_path + " must be a directory")
			}
		}
	} else {
		return errors.New("Thumbs folder doesn't exist or is not a Folder")
	}

	return err
}
示例#15
0
func main() {
	image1Ptr := flag.String("i1", "", "input image 1")
	image2Ptr := flag.String("i2", "", "input image 2")
	image1OutPtr := flag.String("o1", "", "output image 1")
	image2OutPtr := flag.String("o2", "", "output image 2")

	flag.Parse()

	if *image1Ptr == "" {
		log.Fatal("Need to provide i1 flag for path to image 1")
	}

	if *image2Ptr == "" {
		log.Fatal("Need to provide i2 flag for path to image 2")
	}

	image1File, err := os.Open(*image1Ptr)
	if err != nil {
		log.Fatalf("Failed to open image %s, %v", *image1Ptr, err)
	}
	defer image1File.Close()

	image2File, err := os.Open(*image2Ptr)
	if err != nil {
		log.Fatalf("Failed to open image %s, %v", *image2Ptr, err)
	}
	defer image2File.Close()

	im1, _, err := image.Decode(image1File)
	if err != nil {
		log.Fatalf("Failed to decode image %v", err)
	}

	im2, _, err := image.Decode(image2File)
	if err != nil {
		log.Fatalf("Failed to decode image %v", err)
	}

	hash1 := phash.GreyscaleDctMatrix(im1)
	hash2 := phash.GreyscaleDctMatrix(im2)

	distance := phash.HammingDistance(hash1, hash2)

	log.Printf("Image 1 hash: %x\n", hash1)
	log.Printf("Image 2 hash: %x\n", hash2)
	log.Printf("Hamming Distance: %d", distance)

	if *image1OutPtr != "" {
		im1 := phash.HashToImage(hash1)
		out, _ := os.Create(*image1OutPtr)
		var opt jpeg.Options
		opt.Quality = 100
		_ = jpeg.Encode(out, im1, &opt) // put quality to 80%
	}

	if *image2OutPtr != "" {
		im2 := phash.HashToImage(hash2)
		out, _ := os.Create(*image2OutPtr)
		var opt jpeg.Options
		opt.Quality = 100
		_ = jpeg.Encode(out, im2, &opt) // put quality to 80%
	}
}