Exemple #1
0
// image: The image must use this form key name
// w: Desired width of the image
// h: Desired height of the image
func cropImage(w http.ResponseWriter, r *http.Request) {

	defer func() {
		if err := recover(); err != nil {
			http.Error(w, fmt.Sprintf("%s", err), 400)
		}
	}()

	file, header, err := r.FormFile("image")
	if err != nil {
		http.Error(w, "Cannot read image data", 400)
	}
	cWidth := r.FormValue("w")
	cHeight := r.FormValue("h")

	if cWidth == "" || cHeight == "" {
		http.Error(w, "Must supply both width and height", 400)
	} else {
		originalImage, err := ioutil.ReadAll(file)
		if err != nil {
			http.Error(w, "Cannot read image data", 400)
		}
		cWidth, err := strconv.Atoi(cWidth)
		if err != nil {
			http.Error(w, "Bad value for crop width supplied", 400)
		}
		cHeight, err := strconv.Atoi(cHeight)
		if err != nil {
			http.Error(w, "Bad value for crop height supplied", 400)
		}
		log.Printf("Recieved %s, Desired Width and height: %d, %d\n", header.Filename, cHeight, cWidth)

		// Call the crop.Crop() function passing the Response Writer object
		// to it
		// XXX: Add proper error handling via recover()
		crop.Crop(originalImage, cWidth, cHeight, w)
	}
}
Exemple #2
0
func cropper(inputFilePath string, cWidth int, cHeight int, done chan Result) {

	// Recover from any panic here so that one bad image doesn't bring the entire
	// program down
	defer func() {
		if err := recover(); err != nil {
			done <- Result{FilePath: inputFilePath, Error: fmt.Sprintf("%s", err)}
		}
	}()

	imageData, _ := ioutil.ReadFile(inputFilePath)
	croppedFileDir, fileName := filepath.Split(inputFilePath)
	croppedFileName := fmt.Sprintf("%scropped_%s", croppedFileDir, fileName)
	croppedFile, _ := os.Create(croppedFileName)
	defer croppedFile.Close()

	croppedFileWriter := bufio.NewWriter(croppedFile)
	crop.Crop(imageData, cWidth, cHeight, croppedFileWriter)
	croppedFileWriter.Flush()

	// We are done with this file
	done <- Result{FilePath: inputFilePath, Error: ""}
}
Exemple #3
0
func ExampleCrop() {
	// Test image to crop
	inputFilePath := "../test_images/cat1.jpg"
	imageData, err := ioutil.ReadFile(inputFilePath)
	if err != nil {
		log.Fatal("Cannot open file", err)
	}

	// Write the cropped image to a file cropped_cat1.jpg
	croppedFileDir, fileName := filepath.Split(inputFilePath)
	croppedFileName := fmt.Sprintf("%scropped_%s", croppedFileDir, fileName)
	croppedFile, err := os.Create(croppedFileName)
	if err != nil {
		log.Fatal("Could not create file for cropped image")
	}
	defer croppedFile.Close()

	croppedFileWriter := bufio.NewWriter(croppedFile)
	// Crop width and height
	cWidth := 5000
	cHeight := 4000
	crop.Crop(imageData, cWidth, cHeight, croppedFileWriter)
	croppedFileWriter.Flush()
}