bergben / ng2-img-max

Angular 2 module to resize images down to a certain width and height or to reduce the quality to fit a certain maximal filesize - all in the browser.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

File Type Question

mastarenee opened this issue · comments

this.ng2ImgMaxService.resizeImage( IMAGE_FILE_HERE , 2000, 1000)

Can IMAGE_FILE_HERE be an image data uri such as data:image/jpeg;base64,/-- string information --?

Hey there @mastarenee .

Unfortunately only a File can be passed here. You can however convert a DataURI to a File.

All you have to do is create a Blob out of the DataURI, which you could do as described here https://stackoverflow.com/questions/4998908/convert-data-uri-to-file-then-append-to-formdata
(not tested). Since this SO question is a bit outdated, to offer an alternative solution:
You could create a HTMLCanvasElement out of the DataURI as shown in this example jsFiddle https://jsfiddle.net/darul75/w6hdtp24/
(Full blog post http://www.darul.io/post/2016-01-14_canvas-image-and-data-uri)
HTMLCanvasElement has a method toBlob, see https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob. Make sure to include the polyfill as described in the link if you use this method.

To avoid type errors with TypeScript (File vs Blob) you can cast a Blob to a File. You can simply use the function I have created for that purpose: https://github.com/bergben/ng2-img-max/blob/master/src/img-max-size.service.ts#L93

Please let me know if that helps you and solves the problem.

@bergben Ok thanks for the workaround, after I have converted it to a file successfully when I feed it into the resize image function nothing happens now.

My file looks like this output into the console log:
Blob { name: "myimage.jpg", lastModified: 1497010723, size: 156517, type: "image/jpeg" }

// Generate File 
var file = this.blobToFile(myblob, "myimage.jpg", timestamp);

// Resize it
this.ng2ImgMaxService.resizeImage(file, 2000, 1000).subscribe(result => {
       //all good, result is a file
       console.log("Finished Result");
       console.info(result);
    }, error => {
       //something went wrong
       //use result.compressedFile or handle specific error cases individually
       console.log("Error Result");
       console.log(error);
    });

    console.log("File Complete 2");

After running it, I only get back "File Complete 2", Not sure what I'm doing wrong here.

There has to be some sort of output, like at least an error or something in the console?

Nope, nothing comes out, it seems to be getting completely ignored or something. Not sure why.

Can you post all of your code regarding this matter?

// Imports
import { Component, EventEmitter, Input, Output, OnInit, ViewChild, ViewContainerRef, ViewEncapsulation, TemplateRef} from '@angular/core';
import { DatePipe } from '@angular/common';
import { Http, Headers, RequestOptions } from '@angular/http';
import { FormBuilder, Validators } from '@angular/forms';
import { Routes,Router, RouterModule, ActivatedRoute } from '@angular/router';
import { CompleterCmp, CompleterData, CompleterService, CompleterItem } from 'ng2-completer';
import { Ng2ImgMaxService } from 'ng2-img-max';

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';

// Language
import { EN } from 'app/lang/en';

@Component({
  templateUrl: 'add.component.html',
  providers:[EN, DatePipe],
})
export class AddComponent implements OnInit{

	constructor(private http: Http, public fb: FormBuilder, public router: Router, private activatedRoute: ActivatedRoute, public en: EN, private datePipe: DatePipe, private completerService: CompleterService, private ng2ImgMaxService: Ng2ImgMaxService) {}


	dataURItoBlob(dataURI) {
	
		// convert base64 to raw binary data held in a string
		// doesn't handle URLEncoded DataURIs - see SO answer #6850276 for code that does this
		var byteString = atob(dataURI.split(',')[1]);

		// separate out the mime component
		var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]

		// write the bytes of the string to an ArrayBuffer
		var ab = new ArrayBuffer(byteString.length);

		// write the ArrayBuffer to a blob, and you're done
		var blob = new Blob([ab], {type: mimeString});
		return blob;

	}

	blobToFile(theBlob: Blob, name:string, lastModified: number): File {
	
		let file: any = theBlob;
		file.name = name;
		file.lastModified = lastModified;

		//Cast to a File() type
		return <File>theBlob;
		
	}

	resizeImage(event){

		let newWidth = 1000;
		let newHeight = 800;

		console.log(event);
		
		// event.src contains our image uri from ng2-image-upload
		// https://github.com/aberezkin/ng2-image-upload

		var myblob = this.dataURItoBlob( event.src );
		var timestamp = Math.round(new Date().getTime()/1000);
		var file = this.blobToFile(myblob, "myimage.jpg", timestamp);
		console.log("File Complete");
		console.log(myblob);
		console.log(file);
		
		// Image resizer api information
		// https://github.com/bergben/ng2-img-max

		this.ng2ImgMaxService.resizeImage(file, 2000, 1000).subscribe(result => {
		   //all good, result is a file
		   console.log("Finished Result");
		   console.info(result);
		}, error => {
		   //something went wrong
		   //use result.compressedFile or handle specific error cases individually
		   console.log("Error Result");
		   console.log(error);
		});

		console.log("File Complete 2");

	}

	ngOnInit() {}

}

@mastarenee There you go: http://plnkr.co/edit/0iPl62HfE2rtQUVbJpN9?p=preview

Your dataURItoBlob function doesn't seem to work. Use the one in my plnkr instead:

  private dataURItoBlob(dataURI) {
    // convert base64 to raw binary data held in a string
    // doesn't handle URLEncoded DataURIs - see SO answer #6850276 for code that does this
    var byteString = atob(dataURI.split(',')[1]);

    // separate out the mime component
    var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];

    // write the bytes of the string to an ArrayBuffer
    var ab = new ArrayBuffer(byteString.length);
    var ia = new Uint8Array(ab);
    for (var i = 0; i < byteString.length; i++) {
        ia[i] = byteString.charCodeAt(i);
    }

    //New Code
    return new Blob([ab], {type: mimeString});
}

That should solve it. I'll close this :)