Giter VIP home page Giter VIP logo

brunobar79 / j-i-c Goto Github PK

View Code? Open in Web Editor NEW
854.0 41.0 196.0 5.42 MB

J I C is a Javascript Image Compressor using HTML5 Canvas & File API that allows you to compress your jpeg & png images before uploading to the server (100% client-side and no extra libraries required!)

Home Page: http://makeitsolutions.com/labs/jic/

License: MIT License

CSS 14.04% JavaScript 62.03% PHP 4.71% HTML 19.21%

j-i-c's Introduction

J I C

J I C is a Javascript Image Compressor using HTML5 Canvas & File API that allows you to compress your jpeg, png, and webp images before uploading to the server (100% client-side and no extra libraries requried!)

Could you imagine how much bandwidth we can save if Google, Twitter and r Facebook implement this image compression before we upload those 5MB photos? This approach will make the internet faster!!

You can check the working demo here : http://makeitsolutions.com/labs/jic/

Requirements or Dependencies

  • NONE

Install via NPM

npm install j-i-c

Install via Bower

bower install JIC

How it works

To compress the image, first it converts an image object to canvas and then compress it with the canvas method toDataURL(mimetype, quality)

Then to upload the image object it uses the XMLHTTPRequest method sendAsBinary and sends the data url of the compressed image to the server and that's all!! Easy huh?

Example

J I C has only 2 methods: compress & upload. Check it out:

//========= Step 1 - Client Side Compression ===========

//Images Objects
var source_img = document.getElementById("source_img"),
    target_img = document.getElementById("target_img");

//(NOTE: see the examples/js/demo.js file to understand how this object could be a local image 
//from your filesystem using the File API)

//An Integer from 0 to 100
var quality =  80,
// output file format (jpg || png || webp)
output_format = 'jpg', 
//This function returns an Image Object 
target_img.src = jic.compress(source_img,quality,output_format).src;  


//======= Step 2 - Upload compressed image to server =========

//Here we set the params like endpoint, var name (server side) and filename
var server_endpoint = 'upload.php',
	server_var_name = 'file',
	filename = "new.jpg";

//This is the callback that will be triggered once the upload is completed
var callback = function(response){ console.log(response); }

//Here goes the magic
jic.upload(target_img, server_endpoint, server_var_name, filename, callback);

//=======  Optional parameters example: errorCallback, duringCallback and customHeaders ======= 
// This function gets called on an error response of the server - status code of >= 400.
var errorCallback = function () {
	// Handle upload failure
};

// This function gets called while the file is uploading. Returns the percent completeness of the image being uploaded
var duringCallback = function (progressPercent) {
	//progressPercent can be used to show a progress bar
};

// Custom Request Headers, nifty for things like Basic Authorization

var customHeaders = { 'Authorization': 'Basic someBase64EncodedHash=====' };

jic.upload(target_img, server_endpoint, server_var_name, filename, successCallback, errorCallback, duringCallback, customHeaders);

Collaborators

License

This code is released under the MIT License license

Copyright (c) 2012 Bruno Barbieri

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Enjoy!

j-i-c's People

Contributors

alastairparagas avatar brunobar79 avatar dimitriwalters avatar ergec avatar genesiscz avatar sangaman avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

j-i-c's Issues

Not Working when i upload file

I'm trying to use this library but without dropping an image
I upload image file and return base64 of it
and remove the uploaded file
Then i set this base64 to img
i also make another img as result image
when I call the function of compress
give me that error

Uncaught TypeError: Failed to execute 'drawImage' on 'CanvasRenderingContext2D': The provided value is not of type '(HTMLImageElement or HTMLVideoElement or HTMLCanvasElement or ImageBitmap)'

can I use it without using img
i give it base64 and it return base64 to me

Multiple File Uploads

Please inform me how do i compress multiple images.

I have made an online gallery where people can upload multiple images at once and i want that the entire images be compressed before being uploaded.

Alpha channel

In brief examination it looks like the code only outputs jpeg regardless of input.
As jpeg does not support an alpha channel that would seem to present a problem
for images that contain transparent segments. Obviously since the compression leverages jpeg it would seem a little hocus pocus is in order.

Just happens to be the programming task at hand here tonight is compressing .png with alpha channel intact, so I'll venture a germinating thought that may or may not bare fruit.

The idea that will be tested is to make a mask of the transparent area, do the compression via jpeg as normal, BUT then re-merge the transparent area and output in the original image format, hopefully realizing both some compression benefit and retaining alpha channel too, while also keeping the code's footprint munchkin sized.

the duringCallback doesn't work for me

hi, thanks for the code!! it works fine for me. But i came out with a problem while using it.
in my code, i try to use as follow:
jic.upload(img, "/uploadImge", "image", "t."+output_format, uploadImg1, errorCallback, duringCallback, customHeaders);
and
var duringCallback = function (progressPercent) { $("#percent").html(progressPercent); };
but it seems that it never invoke the duringCallback to show the progressPercent. can you tell me how to use it.
Thanks!

Target Image Size Parameter

Hello, how hard is it to add a target image size (file size) parameter?

Instead of guessing at what quality will achieve what size.

My own head can think of a binary search algorithm whereby it tries 5-6 iterations attempting to get just under the target max file size. I can use your library to achieve this. But if you have a easier way based on your inside knowledge can we make this a feature?

Error while uploading

Hi ,when i try to upload my image i've got this error :

InvalidCharacterError: String contains an invalid character JIC.js:105

in atob(data)

Thks

How to use with file input

Hi, i cannot figure out how to compress pictures chosen via the input type file, i tried creating a var = new Image() and setting its path to that of the image but it won't work.
Please help

How do I use this with npm?

I'm importing it like: import jic from 'j-i-c'; but I get this error when trying to use it: _jIC2.default.compress is not a function

compression not working in firefox

Compression is working in chrome, but some unknown reasons not working in firefox, if i debug the js for first time i can able to upload image otherwise image becomes corrupted.
This is the "https://s3-us-west-2.amazonaws.com/cdndev.mylyapp.com/uploadeddocs/gallery/motherdaughtersymboltattooideas10022201753516.jpg" link of image.

Here is the code snippet.

                    i = new Image();
                    c = new Image();
                    t = new Image();
                    if (file.type == "image/png") {
                        output_format = "png";
                    }
                    i.src = base64;// original image converted in base64

                    c.src = jic.compress(i, objVariables.ImageQuality, output_format, i.width, i.height).src;
                    var obj=objUtility.compressedHeightWidth(i);
                    t.src = jic.compress(i, objVariables.ImageQuality, output_format, parseInt(obj.Width), parseInt(obj.Height)).src;
                    var blobs = [];

                    blobs.push({ src: i.src, path: S3GalleryBucketOriginal});
                    blobs.push({ src: t.src, path: S3GalleryBucketCompress });
                    blobs.push({ src: c.src, path: S3GalleryBucket});

Support for other formats.

Hi,

Thanks for this awesome library!

Do you plan for any support for other types of images, like BMP and gif? Would be awesome to see a huge size reduction for these image types!

You Will Not support for iPhone iOS Safari

have any method?

if your upload file large than 2M size. canvas will be broken on Safari

I've experienced the same problem. It seems that this is an iOS limitation, jpg over 2 megapixel are subsampled.

See Creating Compatible Web Content for Safari on IPhone
https://developer.apple.com/library/ios/documentation/AppleApplications/Reference/SafariWebContent/CreatingContentforSafarioniPhone/CreatingContentforSafarioniPhone.html

https://stackoverflow.com/questions/11929099/html5-canvas-drawimage-ratio-bug-ios

Incorrect 'quality' value in example provided

In the example code you provided, you specify the value of 'quality' as having to be an integer from 0 to 100, when it really should be a floating point value from 0 to 1:

//An Integer from 0 to 100
var quality = 80;
...
//This function returns an Image Object
target_img.src = jic.compress(source_image,quality).src;

Took me a little while to figure out why the compression wasn't working correctly for me, until I took a look at the source code on your demo page :)

Using JIC.js compress an image in python-flaks application

Hey , I am using JIC.js library for image compression and uploading it,
I need to accept this compressed image into python code.
Currently I am using request.files['imgInp'] to accept input.
How can i get compressed image?

This is my javascript code

     function readURL(input) {
        if (input.files && input.files[0]) {
        var output_format = "jpg";
        var file = input.files[0], 
        reader = new FileReader();
        reader.onload = function(event) {
        var i = document.getElementById("source_image");
            i.src = event.target.result;
            i.onload = function(){
                image_width=$(i).width(),
                image_height=$(i).height();

                if(image_width > image_height){
                    i.style.width="320px";
                }else{
                    i.style.height="300px";
                }
                i.style.display = "block";
                console.log("Image loaded");
            }             
        };     
        if(file.type=="image/png"){
            output_format = "png";
        }
        console.log("Filename:" + file.name);
        console.log("Filesize:" + (parseInt(file.size) / 1024) + " Kb");
        console.log("Type:" + file.type);         
        reader.readAsDataURL(file);

        ///////////////////////////////////////////////////////////////////////////////////////
        var result_image = document.getElementById('result_image');
        var source_image = document.getElementById('source_image');
        if (source_image.src == "") {
            alert("You must load an image first!");
            return false;
        }
        console.log("process start...");
        result_image.src = jic.compress(source_image,30,output_format).src;
        result_image.onload = function(){
            var image_width=$(result_image).width(),
            image_height=$(result_image).height();                 
            if(image_width > image_height){
                result_image.style.width="320px";
            }else{  
                result_image.style.height="300px";
            }
           result_image.style.display = "block";
        }
        console.log("process finished...");         
    }        

};

This is my html code

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="/static/JIC.js"></script>

your image

your image

This is python code

@app.route('/updateuser',methods=['GET','POST'])
def updateuser():
file = request.files['imgInp']

Is this project still alive?

This project is one of the best ideas for bandwidth saving of all time... IMHO, for sure.
But it's 4 years since last release and many issues open without feedback.
Is there still any interest in keeping it active by the owners?

file size differ only download

After compression When i download the file the size is reduced to half of the original file(approximately).
If I upload that compress file the size does not vary like download.

Safari/Firefox Issues

Right now working on an angular2 app. I'm using J-I-C for compression before uploading to firebase storage. It works perfectly on Chrome. On other browsers it doesn't seem to process properly.

...
this.compressedImage = jic.compress(imgTag, quality, 'jpg').src;
// on safari this.compressedImage  = "data:"

let file = dataURItoBlob(this.compressedImage);

let uploadTask = storageRef.child('images/' + newKey + fileType)
          .put(file);
...

JIC error

Hey after reading your answer on SO I tried using JIC but I am currently getting the following error when I select a file which should get compressed;

(index):109 Uncaught TypeError: Failed to execute 'drawImage' on 'CanvasRenderingContext2D': The provided value is not of type '(CSSImageValue or HTMLImageElement or SVGImageElement or HTMLVideoElement or HTMLCanvasElement or ImageBitmap or OffscreenCanvas)'

I have also left a question related to this problem here

Any advice on why I am getting such an error. I am actually quite new to JS itself hence I am a bit slow in error handling.

Security issue.

Great source available. However there is an error on the below line any support can be expected please.

var newImageData = canvas.toDataURL(mime_type, quality/100);

Error on console:

Uncaught SecurityError: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.

Here is my code:

sample.txt

Not working in firefox

I'm using the library to compress images. I started with creating the source element like so:

var img_elem = document.createElement('img');
    img_elem.src = canvas.toDataURL();

The img_elem, when logged, shows that the element actually has the src attribute filled, so up to this point it all works.

Then, I put it through the compressor:

var compressed = document.createElement('img');
    compressed.src = jic.compress(img_elem, 90, 'jpg').src;

Now, when I log compressed it shows:

<img src="data:,">

Link broken in README.md

Hello :)

Trying to see the working example at link in the README, I came across the following error page:
screen shot 2018-07-18 at 2 44 12 pm

Just wanted to see if this was an error, or maybe the examples moved elsewhere.

A Bug or A Functionality Missing, depending on how you consider it.

    compress: function(source_img_obj, quality, output_format){

         var mime_type = "image/jpeg";
         if(typeof output_format !== "undefined" && output_format=="png"){
            mime_type = "image/png";
         }

         console.log(source_img_obj);
         var cvs = document.createElement('canvas');
         cvs.width = source_img_obj.naturalWidth;
         cvs.height = source_img_obj.naturalHeight;
         console.log(cvs.width, cvs.height, source_img_obj.width);
         var ctx = cvs.getContext("2d").drawImage(source_img_obj, 0, 0);
         var newImageData = cvs.toDataURL(mime_type, quality/100);
         console.log('data URL:', newImageData);
         var result_image_obj = new Image();
         result_image_obj.src = newImageData;
         return result_image_obj;
    },

You query naturalWidth and naturalHeight here. Both values could be 0 if they are not available.

This case happened to me.

Though this may not be considered as a strict bug on jic.js side, the caller should make sure source_img_obj meets assumptions.

But it's better to include some validity checking for such a case, for better user/developer experiences.

Also, does anybody know why that naturalWidth and naturalHeight can be zero? I have no idea how to fix this problem.

browse file

Can you make browsing file? because i don't like a drag and drop function!

NS_ERROR_NOT_AVAILABLE:

Hola Estimado brunobar79,

e estado intentado utilizar tu librería sin éxito aun jajajjaja, pero sin duda debe ser un error mio jajaj,

mira me da error NS_ERROR_NOT_AVAILABLE:
en la linea

var ctx = cvs.getContext("2d").drawImage(source_img_obj, 0, 0);

JIC.js (line 37)

y aveces en

var ctx = cvs.getContext("2d").drawImage(compressed_img_obj, 0, 0);

8
JIC.js (line 59)

e modificado el script para que funcione sin drag & drop el script modificado es el siguiente.

jQuery(function(){
jQuery(':file').change(function(e){
var file = this.files[0],
reader = new FileReader();
reader.onload = function(event) {
var i = document.getElementById("source");
i.src = event.target.result;
i.onload = function(){
image_width=jQuery(i).width(),
image_height=jQuery(i).height();

                if(image_width > image_height){
                        i.style.width="320px";
                }else{
                        i.style.height="300px";
                }
                i.style.display = "block";
                console.log("Image loaded");

        }

    };
    reader.readAsDataURL(file);
    var source_image = document.getElementById('source');
    var result_image = document.getElementById('resultado');
    result_image.src = jic.compress(source_image,75).src;
    result_image.onload = function(){
        var image_width=jQuery(result_image).width(),
            image_height=jQuery(result_image).height();

        if(image_width > image_height){
            result_image.style.width="320px";
        }else{
            result_image.style.height="300px";
        }
       result_image.style.display = "block";


    }

});

});

en el botón de subida el código es el siguiente

var result_image = document.getElementById('resultado');
var callback= function(response){
console.log("image uploaded successfully! :)");
console.log(response);
}
jic.upload(result_image, '/foto/subir/', 'file', 'foto.jpg',callback);

/foto/subir es el script php con zendframework que se encarga de subir la foto resultado de la compresión,

te agradecería muchísimo si me pudieras dar un cable con lo que está pasando, espero estés muy bien me despido

Atte.
GrisUNO

Decleration target_img

:54 Uncaught SyntaxError: Unexpected token .

target_img.src = jic.compress(file,quality,output_format).src;

newImageData is null in iOS

compress: function(source_img_obj, quality, output_format){
var mime_type = "image/jpeg";
if(typeof output_format !== "undefined" && output_format=="png"){
mime_type = "image/png";
}
var cvs = document.createElement("canvas");
cvs.width = source_img_obj.naturalWidth;
cvs.height = source_img_obj.naturalHeight;
cvs.getContext("2d").drawImage(source_img_obj, 0, 0);
var newImageData = cvs.toDataURL(mime_type, quality/100);
var result_image_obj = new Image();
result_image_obj.src = newImageData;
return result_image_obj;
},

I am getting newImageData ==> "data:,"

does this plugin work for iOS?

Scenario : I want to take picture from iPad camera and upload on our server after compressing it.

PNG's getting larger after compression

I can't seem to get it to actually compress a png file on the demo page. I tried the attached file with the default compression ratio of 30 and the file size went from 2765KB for the source file to 4089KB for the "compressed" file. I also tried different compression ratios but they didn't seem to change anything in the output file.

03-23-2016-07-33-20--153290107-02-09-2016-11-53-15--1869943628-image6

Possible large file compression issues

Great library.

I tried the JIC's demo link to upload a large .jpg (size: 4.6mb) file at the link below (after downloading the image onto my computer first)

http://www.kenrockwell.com/nikon/d810/sample-images/810_4051.JPG

At the Compression ratio of 5% or any up to 30% that I've tried, I've gotten output images that ranged between 2 to 4 times the original filesize.

For example:
Compression ratio: 5%
Original filesize: 4764.8720703125 Kb
JIC Compress/uploaded filesize: 14001.7578125 Kb

Am I doing this correctly on your demo site?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.