Skip to content

Instantly share code, notes, and snippets.

@maagmirror
Created December 11, 2015 13:59
Show Gist options
  • Save maagmirror/32f04e90919cd46b9dc8 to your computer and use it in GitHub Desktop.
Save maagmirror/32f04e90919cd46b9dc8 to your computer and use it in GitHub Desktop.
// ==UserScript==
// @name Cropper
// @namespace www.taringa.net/naoko-
// @version 0.2
// @description Corta imagenes desde el Mi
// @author Yo, Fabi
// @match *://www.taringa.net/*
// @grant none
// ==/UserScript==
//Acá va todo
var attTemplate='<li class="imagef"><a class="btn g" title="Cortar imagen"><div class="btn-text"><i class="s-pic"></i></div></a></li>';
var contAttTemplate='<div class="clearfix attach-imagef" style="display: none;padding: 10px;width: 543px;border: 1px solid #CCC;border-radius: 0 0 3px 3px;border-top: 0;position: relative;"><a class="remove-attach floatR"><i class="icon remove-s"></i></a><button class="btn g if-urc simple-btn" style="padding: 6px 10px;margin-top: 1px;">Desde archivo</button><input type="file" style="display:none" class="urlcropp"><br><div class="add-url" style="margin-top: 15px;margin-bottom: -5px;"><input class="simple if-imgurl" type="text" name="url" tabindex="601" placeholder="URL de la imagen o CTRL+V para copiar del portapapeles" autocomplete="off"></div><div class="if-CropArea" style="margin-top:10px;"></div></div>';
(function($){
//Add Cropper
$('head').append('<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/cropper/0.9.1/cropper.min.css">');
$.getScript('https://cdnjs.cloudflare.com/ajax/libs/cropper/0.9.1/cropper.min.js');
//Internal
$.fn.addButton=function(cl,title,top){
var btnTemplate='<button class="btn %class%">%title%</button>';
if(typeof top=='undefined'){
this.append(btnTemplate.replace('%class%',cl).replace('%title%',title));
}
else{
this.prepend(btnTemplate.replace('%class%',cl).replace('%title%',title));
}
return this;
};
$.fn.addCropper=function(img){
var croppTemplate='<div class="if-container"><img src="%img%" style="height:100%;width:100%;"></div>';
console.log(img);
this.html(croppTemplate.replace('%img%',img));
this.show();
$('.if-container > img').cropper({ aspectRatio:NaN,autoCropArea: 0.99,strict:true});
$('.if-upload, .if-changeimg').show();
return this;
};
//end internal
$(document).ready(function(){
if (!String.prototype.startsWith) {
String.prototype.startsWith = function(searchString, position) {
position = position || 0;
return this.indexOf(searchString, position) === position;
};
}
//$('.my-shout-attach-options > li.image').hide();
$('.my-shout-attach-options').prepend(attTemplate);
$('.my-shout-content-mi').prepend(contAttTemplate);
$('.imagef i.s-pic').css({'background':'url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAACPUlEQVR4nO3av4oTURiG8Z+LiIWIhYhl2MJCvIBli2BwsViwsfQG7LwNEWtrsbJUENFCb0KwEQm66IJiI26xnRbjQDYkmT+ZM9/sZB4YSDKHc773yZnJnMkwsNmcqdD2Eh4UtPmAl/XLScYYj3EHP+t2MsLfgu3pmoWmYIw/svo+4srszq2IilpkjNe48P/9dbzH5bxBnwXMh8+5oeZMHTk9h8DstJ/fvmI7b9jHGbDsm4cDTDDNP+ibgErh6ZeAyuHpj4Ba4eHszOuiE9iizoto46S4hbtqhJ+n6AxfZpsP3ESfdbcTZ/tl9OUQmKf0N99HAd9UmPZ9FPBOyfD0U0AlBgHRBUSz8QJmL4QmBW2v4nnF/ov6LGIHD9fsozFG2l0O7+J3iTHXqqGrh8Au3uBi6oG6KGBV+KOmB+uagLHl4T/jftMDdklAvqRdFH6KWzhsetCuCFi1np/Kfk0OUgzcBQFh4YkXEBqeWAHh4YkTUOYeXvLwxAjYk/3UhYfn5FqgDfbwCucX7Kt0A7Mp2pwBnQtPewI6GZ52BHQ2POkFrAp/KLu8DQtPWgG3rQ4/kS1wQkklYF9x+E+Jxq5ECgH7eIFzC/Z1KjzNXwfs4J504Y/xpaDNrzX6X8lI/T8qv+NaqsLaYqRe+B+yp7NOPSM9DJ96LXCEJ4nHqMMjvCW9gG0lHlII4Fn+IvqOUDiDgOgCohkERBcQzSAguoCBaty0Ic8HtMYgILqAaAYB0QVEMwiILiCajRcwsOn8A59h8c0JHMd9AAAAAElFTkSuQmCC)',
'background-position':0,
'background-size': '20px',
'top': '-1px',
'left': '-1px',
});
//Remove Events
$('.attach-imagef').on('click','.remove-attach',function(e){e.preventDefault();e.stopPropagation();$('.if-upload, .if-changeimg').hide();$('.if-urc, .add-url').show();$('.attach-imagef').hide();$('.if-CropArea').html('');cleanInputs();$('.attach-imagef').hide();});
$('.attach-imagef').addButton('a if-upload floatR','Cortar');
$('.attach-imagef').addButton('r if-changeimg floatL','Cambiar imagen');
$('.attach-imagef > .add-url').addButton('g if-urlup simple-btn" style="padding: 6px 10px;margin-top: 1px;"','Desde url');
//dah odio esta pija
$('li.link,li.video,li.image').on('click',function(){
$('.attach-imagef').hide();
});
$('.imagef > a').tipsy();
$('.attach-imagef').on('click','.if-urlup',function(){
var texttg=$('.if-imgurl').val();
if(texttg!='' && texttg.startsWith('http')){
loadToCanvas(texttg);
}
});
$('.attach-imagef').on('click','.if-urc',function(){$('.urlcropp').click();});
$('.if-upload, .if-changeimg').hide();
$('.attach-imagef').on('click','.if-upload',function(){
$('html, body').animate({
scrollTop: $(".shout-box").offset().top
}, 200);
//UploadCanvas
var tCanvas=$('.if-container > img').cropper("getCroppedCanvas").toDataURL();
//Agujero negro
$.ajax({
type: 'post',
url: '/ajax/kn3-signdata.php',
dataType: 'json',
data: {app: 'images'},
beforeSend:function(){
$('.if-upload, .if-changeimg').hide();
$('.if-CropArea').html('<b>Cortando y subiendo...</b>');
},
success:function(r){
var formData = new FormData();
formData.append('file', dataURItoBlob(tCanvas), "a");
for (var temp in r) {
formData.append(temp, r[temp]);
}
var xhr = new XMLHttpRequest();
xhr.open('POST', 'http://apikn3.taringa.net/image/upload', true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
var psrd=JSON.parse(xhr.responseText);
console.log(psrd.url);
$('.my-shout-attach').addClass('attach-image');
$('.my-shout-attach').html(tmpl('template_attach_image_input'));
$('.my-shout-attach').show();
$('input.simple').val(psrd.url);
var el=$('.shout-box[data-in="mi"]');
mi.attach.submitUrl(el,'image');
$('.if-urc, .add-url').show();
$('.attach-imagef').hide();
$('.if-CropArea').html('');
cleanInputs();
}
else if(xhr.status!=200){
$('.if-CropArea').html('<b>Error :\'c</b>');
dummy(xhr.status);
}
}
xhr.send(formData);
},
error:function(err){
$('.if-CropArea').html('<b>Error :\'c</b>');
dummy(err);
}
});
});
$('.attach-imagef').on('click','.if-changeimg',function(){
$('.if-CropArea, .if-upload, .if-changeimg').hide();
cleanInputs();
$('.if-urc, .add-url').show();
$('html, body').animate({
scrollTop: $(".shout-box").offset().top
}, 200);
});
$('.urlcropp').change(function(e){
loadToCanvas(URL.createObjectURL(e.target.files[0]));
$('.if-urc').hide();
$('.add-url').hide();
$('.if-CropArea').show();
});
$('.my-shout-attach-options').on('click','.imagef',function(e){
e.preventDefault();
e.stopPropagation();
$('#uploadImagemi9766Uploader').css({'top':'-1000px'});
$('.my-shout-attach,.dropdown-menu.my-shout-attach-image.select-list').hide();
$('.attach-imagef').show();
});
});
function loadToCanvas(umm){
//Firefox de mierda va a dar la url de la imagen y no el dataurl, por eso no se puede obtener el dataurl
if(!umm.startsWith('http')){
$('.if-urc, .add-url').hide();
$('.if-CropArea').addCropper(umm);
}
else{
convertToBase64FromImgTag(umm, function(base64Img){
if(base64Img.startsWith('data:')){
$('.if-urc, .add-url').hide();
$('.if-CropArea').addCropper(base64Img);
}
else{
alert(base64Img);
}
});
}
}
function cleanInputs(){
var input=$('.urlcropp');
input.replaceWith(input.val('').clone(true));
$('.if-imgurl').val('');
}
//PORTAPAPELES
document.onkeydown = function(e) {return on_keyboard_action(e); }
document.onkeyup = function(e) {return on_keyboardup_action(e); }
//Create Catcher
pasteCatcher=document.createElement('div');
pasteCatcher.setAttribute('id','imgrec');
pasteCatcher.setAttribute('contenteditable', 'true');
pasteCatcher.style.cssText ='opacity:0;position:fixed;top:-1000px;left:0px;';
pasteCatcher.style.marginLeft = "-20px";
document.body.appendChild(pasteCatcher);
var isChrome=(navigator.userAgent.indexOf('hrome')>-1);
pasteCatcher.onpaste=function(ev){
//Chrome no obtiene el dataurl desde el portapapeles si es de un archivo y no lo pega al div
if(isChrome){
if(ev.clipboardData) {
var items = ev.clipboardData.items;
if (items){
for (var i = 0; i < items.length; i++) {
if (items[i].type.indexOf("image") !== -1) {
var blob = items[i].getAsFile();
var URLObj = window.URL || window.webkitURL;
var source = URLObj.createObjectURL(blob);
pasteCatcher.innerHTML='';
loadToCanvas(source);
return;
}
}
}
}
}
else{
//Firefox sí lo hace, pero no se puede obtener la imagen directamente desde el portapapeles
setTimeout(function(){
if(pasteCatcher.lastChild.nodeName.toLowerCase()=="img"){
loadToCanvas(pasteCatcher.lastChild.currentSrc);
}
pasteCatcher.innerHTML='';
}
,500);
}
}
ctrl_pressed=false;
function on_keyboard_action(event){
k = event.keyCode;
//ctrl
if(k==17){
if(ctrl_pressed == false)
ctrl_pressed = true;
if (ctrl_pressed && $('.attach-imagef .add-url').is(':visible')){
pasteCatcher.focus();
}
}
}
function on_keyboardup_action(event){
//ctrl
k = event.keyCode;
if(k==17)
ctrl_pressed = false;
}
//ENDOF PORTAPAPELES
})(jQuery);
//Utils
function dummy(e){
console.log(e);
return;
}
function convertToBase64FromImgTag(url, callback){
$.ajax({
url: 'http://nikumi.ml/upload/getBase64.php',
type: "post",
data:{f:url}
}).done(function( data, textStatus, jqXHR ) {
callback(data);
});
}
function convertImgToBase64URL(url, callback, outputFormat){
var canvas = document.createElement('CANVAS'),
ctx = canvas.getContext('2d'),
img = new Image();
img.crossOrigin = 'Anonymous';
img.onload = function(){
var dataURL;
canvas.height = img.height;
canvas.width = img.width;
ctx.drawImage(img, 0, 0);
dataURL = canvas.toDataURL(outputFormat);
callback(dataURL);
canvas = null;
};
img.src = url;
}
//Tnx Over <3
function dataURItoBlob(dataURI) {
var byteString;
if (dataURI.split(',')[0].indexOf('base64') >= 0)
byteString = atob(dataURI.split(',')[1]);
else
byteString = unescape(dataURI.split(',')[1]);
var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
var ia = new Uint8Array(byteString.length);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
return new Blob([ia], {
type: mimeString
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment