Full Code of josefrichter/resize for AI

master 65df934c1104 cached
7 files
5.3 KB
1.5k tokens
3 symbols
1 requests
Download .txt
Repository: josefrichter/resize
Branch: master
Commit: 65df934c1104
Files: 7
Total size: 5.3 KB

Directory structure:
gitextract_dqoie2sr/

├── .gitignore
├── Gemfile
├── README.txt
├── main.rb
├── public/
│   └── preprocess.js
└── views/
    ├── received.erb
    └── upload.erb

================================================
FILE CONTENTS
================================================

================================================
FILE: .gitignore
================================================
#rails specific
*.sqlite3
config/database.yml
log/*
tmp/*

## generic files to ignore
*~
*.lock
*.DS_Store
*.swp
*.out

public/uploads/*

================================================
FILE: Gemfile
================================================
source 'https://rubygems.org'

gem 'sinatra'


================================================
FILE: README.txt
================================================
12 Sep 2012

Preprocessing (scaling down) images on client side before uploading

Because people often upload 5MB big 3000x2000px PNGs that are then scaled down to 100x100px JPEGs on server - waste of time and bandwidth

1. user selects image(s)
2. script opens the image using FileReader API
3. script appends it to new Image object (not displayed at all actually) 
4. new Image objects is drawn into new Canvas object, that is scaled down to desired dimensions
5. display the canvas, ie. a preview of the image to be uploaded
6. take the pic from canvas as JPEG in dataURI format
7. send it to server
8. save it on server side

(c) Josef Richter

================================================
FILE: main.rb
================================================
require 'rubygems'
require 'sinatra'
require 'base64'

get '/' do
  erb :upload
end

post '/submit' do
  
  newimages = []
  now = Time.now.to_i.to_s #timestamp string
  
  params[:images].each_with_index do |image, index|

    imagedata = image.split(',')[1] #basically remove the header
    filename = 'uploads/'+ now + '_' + (index+1).to_s + '.jpg' #construct the new filename
    
    # write the file
    File.open('public/'+filename, 'wb') do|f|
      f.write(Base64.decode64(imagedata))
    end
    
    newimages << filename
    
  end
  
  erb :received, :locals => {:images => newimages}
  
end

================================================
FILE: public/preprocess.js
================================================
var fileinput = document.getElementById('fileinput');

var max_width = fileinput.getAttribute('data-maxwidth');
var max_height = fileinput.getAttribute('data-maxheight');

var preview = document.getElementById('preview');

var form = document.getElementById('form');

function processfile(file) {
  
    if( !( /image/i ).test( file.type ) )
        {
            alert( "File "+ file.name +" is not an image." );
            return false;
        }

    // read the files
    var reader = new FileReader();
    reader.readAsArrayBuffer(file);
    
    reader.onload = function (event) {
      // blob stuff
      var blob = new Blob([event.target.result]); // create blob...
      window.URL = window.URL || window.webkitURL;
      var blobURL = window.URL.createObjectURL(blob); // and get it's URL
      
      // helper Image object
      var image = new Image();
      image.src = blobURL;
      //preview.appendChild(image); // preview commented out, I am using the canvas instead
      image.onload = function() {
        // have to wait till it's loaded
        var resized = resizeMe(image); // send it to canvas
        var newinput = document.createElement("input");
        newinput.type = 'hidden';
        newinput.name = 'images[]';
        newinput.value = resized; // put result from canvas into new hidden input
        form.appendChild(newinput);
      }
    };
}

function readfiles(files) {
  
    // remove the existing canvases and hidden inputs if user re-selects new pics
    var existinginputs = document.getElementsByName('images[]');
    var existingcanvases = document.getElementsByTagName('canvas');
    while (existinginputs.length > 0) { // it's a live list so removing the first element each time
      // DOMNode.prototype.remove = function() {this.parentNode.removeChild(this);}
      form.removeChild(existinginputs[0]);
      preview.removeChild(existingcanvases[0]);
    } 
  
    for (var i = 0; i < files.length; i++) {
      processfile(files[i]); // process each file at once
    }
    fileinput.value = ""; //remove the original files from fileinput
    // TODO remove the previous hidden inputs if user selects other files
}

// this is where it starts. event triggered when user selects files
fileinput.onchange = function(){
  if ( !( window.File && window.FileReader && window.FileList && window.Blob ) ) {
    alert('The File APIs are not fully supported in this browser.');
    return false;
    }
  readfiles(fileinput.files);
}

// === RESIZE ====

function resizeMe(img) {
  
  var canvas = document.createElement('canvas');

  var width = img.width;
  var height = img.height;

  // calculate the width and height, constraining the proportions
  if (width > height) {
    if (width > max_width) {
      //height *= max_width / width;
      height = Math.round(height *= max_width / width);
      width = max_width;
    }
  } else {
    if (height > max_height) {
      //width *= max_height / height;
      width = Math.round(width *= max_height / height);
      height = max_height;
    }
  }
  
  // resize the canvas and draw the image data into it
  canvas.width = width;
  canvas.height = height;
  var ctx = canvas.getContext("2d");
  ctx.drawImage(img, 0, 0, width, height);
  
  preview.appendChild(canvas); // do the actual resized preview
  
  return canvas.toDataURL("image/jpeg",0.7); // get the data from canvas as 70% JPG (can be also PNG, etc.)

}


================================================
FILE: views/received.erb
================================================
<%# params[:images].each do |img| %>
  <!-- <img src="<%#= img %>"/> -->
<%# end %>

<!-- anyway, better do the above I guess  -->
<% images.each do |img| %>
  <img src="<%= img %>">
<% end %>

================================================
FILE: views/upload.erb
================================================
<form id="form" action="submit" method="post" accept-charset="utf-8" enctype="multipart/form-data">
  <input id="fileinput" data-maxwidth="620" data-maxheight="620" type="file" name="file[]" multiple/>
  <input type="submit" value="Upload &rarr;">
</form>

<div id="preview"></div>

<script src="preprocess.js" type="text/javascript" charset="utf-8"></script>
Download .txt
gitextract_dqoie2sr/

├── .gitignore
├── Gemfile
├── README.txt
├── main.rb
├── public/
│   └── preprocess.js
└── views/
    ├── received.erb
    └── upload.erb
Download .txt
SYMBOL INDEX (3 symbols across 1 files)

FILE: public/preprocess.js
  function processfile (line 10) | function processfile(file) {
  function readfiles (line 44) | function readfiles(files) {
  function resizeMe (line 73) | function resizeMe(img) {
Condensed preview — 7 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (6K chars).
[
  {
    "path": ".gitignore",
    "chars": 136,
    "preview": "#rails specific\n*.sqlite3\nconfig/database.yml\nlog/*\ntmp/*\n\n## generic files to ignore\n*~\n*.lock\n*.DS_Store\n*.swp\n*.out\n\n"
  },
  {
    "path": "Gemfile",
    "chars": 45,
    "preview": "source 'https://rubygems.org'\n\ngem 'sinatra'\n"
  },
  {
    "path": "README.txt",
    "chars": 647,
    "preview": "12 Sep 2012\n\nPreprocessing (scaling down) images on client side before uploading\n\nBecause people often upload 5MB big 30"
  },
  {
    "path": "main.rb",
    "chars": 604,
    "preview": "require 'rubygems'\nrequire 'sinatra'\nrequire 'base64'\n\nget '/' do\n  erb :upload\nend\n\npost '/submit' do\n  \n  newimages = "
  },
  {
    "path": "public/preprocess.js",
    "chars": 3416,
    "preview": "var fileinput = document.getElementById('fileinput');\n\nvar max_width = fileinput.getAttribute('data-maxwidth');\nvar max_"
  },
  {
    "path": "views/received.erb",
    "chars": 192,
    "preview": "<%# params[:images].each do |img| %>\n  <!-- <img src=\"<%#= img %>\"/> -->\n<%# end %>\n\n<!-- anyway, better do the above I "
  },
  {
    "path": "views/upload.erb",
    "chars": 360,
    "preview": "<form id=\"form\" action=\"submit\" method=\"post\" accept-charset=\"utf-8\" enctype=\"multipart/form-data\">\n  <input id=\"fileinp"
  }
]

About this extraction

This page contains the full source code of the josefrichter/resize GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 7 files (5.3 KB), approximately 1.5k tokens, and a symbol index with 3 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!