Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP

Comparing changes

Choose two branches to see what’s changed or to start a new pull request. If you need to, you can also compare across forks.

Open a pull request

Create a new pull request by comparing changes across two branches. If you need to, you can also compare across forks.
base fork: show555/resize.jsx
base: 74aaf37af9
...
head fork: show555/resize.jsx
compare: 014e4bd0ce
  • 3 commits
  • 4 files changed
  • 0 commit comments
  • 1 contributor
Commits on Dec 27, 2013
@show555 改行コードをLF(Unix)に統一 5afc3e0
@show555 Underscore.jsのバージョンアップ・細かい修正
Underscore.jsのバージョンを1.4.4→1.5.2へ変更。
Photoshopの設定単位を保存し、処理後に復元するよう変更。
4e8882e
Commits on Jan 15, 2014
@show555 処理中に進捗バーを表示する機能を追加 014e4bd
View
197 src/underscore.inc
@@ -1,7 +1,6 @@
-// Underscore.js 1.4.4
+// Underscore.js 1.5.2
// http://underscorejs.org
-// (c) 2009-2011 Jeremy Ashkenas, DocumentCloud Inc.
-// (c) 2011-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
+// (c) 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
// Underscore may be freely distributed under the MIT license.
(function() {
@@ -9,7 +8,7 @@
// Baseline setup
// --------------
- // Establish the root object, `window` in the browser, or `global` on the server.
+ // Establish the root object, `window` in the browser, or `exports` on the server.
var root = this;
// Save the previous value of the `_` variable.
@@ -66,7 +65,7 @@
}
// Current version.
- _.VERSION = '1.4.4';
+ _.VERSION = '1.5.2';
// Collection Functions
// --------------------
@@ -79,14 +78,13 @@
if (nativeForEach && obj.forEach === nativeForEach) {
obj.forEach(iterator, context);
} else if (obj.length === +obj.length) {
- for (var i = 0, l = obj.length; i < l; i++) {
+ for (var i = 0, length = obj.length; i < length; i++) {
if (iterator.call(context, obj[i], i, obj) === breaker) return;
}
} else {
- for (var key in obj) {
- if (_.has(obj, key)) {
- if (iterator.call(context, obj[key], key, obj) === breaker) return;
- }
+ var keys = _.keys(obj);
+ for (var i = 0, length = keys.length; i < length; i++) {
+ if (iterator.call(context, obj[keys[i]], keys[i], obj) === breaker) return;
}
}
};
@@ -285,7 +283,8 @@
return result.value;
};
- // Shuffle an array.
+ // Shuffle an array, using the modern version of the
+ // [Fisher-Yates shuffle](http://en.wikipedia.org/wiki/Fisher窶添ates_shuffle).
_.shuffle = function(obj) {
var rand;
var index = 0;
@@ -298,6 +297,16 @@
return shuffled;
};
+ // Sample **n** random values from an array.
+ // If **n** is not specified, returns a single random element from the array.
+ // The internal `guard` argument allows it to work with `map`.
+ _.sample = function(obj, n, guard) {
+ if (arguments.length < 2 || guard) {
+ return obj[_.random(obj.length - 1)];
+ }
+ return _.shuffle(obj).slice(0, Math.max(0, n));
+ };
+
// An internal function to generate lookup iterators.
var lookupIterator = function(value) {
return _.isFunction(value) ? value : function(obj){ return obj[value]; };
@@ -308,9 +317,9 @@
var iterator = lookupIterator(value);
return _.pluck(_.map(obj, function(value, index, list) {
return {
- value : value,
- index : index,
- criteria : iterator.call(context, value, index, list)
+ value: value,
+ index: index,
+ criteria: iterator.call(context, value, index, list)
};
}).sort(function(left, right) {
var a = left.criteria;
@@ -319,38 +328,41 @@
if (a > b || a === void 0) return 1;
if (a < b || b === void 0) return -1;
}
- return left.index < right.index ? -1 : 1;
+ return left.index - right.index;
}), 'value');
};
// An internal function used for aggregate "group by" operations.
- var group = function(obj, value, context, behavior) {
- var result = {};
- var iterator = lookupIterator(value == null ? _.identity : value);
- each(obj, function(value, index) {
- var key = iterator.call(context, value, index, obj);
- behavior(result, key, value);
- });
- return result;
+ var group = function(behavior) {
+ return function(obj, value, context) {
+ var result = {};
+ var iterator = value == null ? _.identity : lookupIterator(value);
+ each(obj, function(value, index) {
+ var key = iterator.call(context, value, index, obj);
+ behavior(result, key, value);
+ });
+ return result;
+ };
};
// Groups the object's values by a criterion. Pass either a string attribute
// to group by, or a function that returns the criterion.
- _.groupBy = function(obj, value, context) {
- return group(obj, value, context, function(result, key, value) {
- (_.has(result, key) ? result[key] : (result[key] = [])).push(value);
- });
- };
+ _.groupBy = group(function(result, key, value) {
+ (_.has(result, key) ? result[key] : (result[key] = [])).push(value);
+ });
+
+ // Indexes the object's values by a criterion, similar to `groupBy`, but for
+ // when you know that your index values will be unique.
+ _.indexBy = group(function(result, key, value) {
+ result[key] = value;
+ });
// Counts instances of an object that group by a certain criterion. Pass
// either a string attribute to count by, or a function that returns the
// criterion.
- _.countBy = function(obj, value, context) {
- return group(obj, value, context, function(result, key) {
- if (!_.has(result, key)) result[key] = 0;
- result[key]++;
- });
- };
+ _.countBy = group(function(result, key) {
+ _.has(result, key) ? result[key]++ : result[key] = 1;
+ });
// Use a comparator function to figure out the smallest index at which
// an object should be inserted so as to maintain order. Uses binary search.
@@ -387,7 +399,7 @@
// allows it to work with `_.map`.
_.first = _.head = _.take = function(array, n, guard) {
if (array == null) return void 0;
- return (n != null) && !guard ? slice.call(array, 0, n) : array[0];
+ return (n == null) || guard ? array[0] : slice.call(array, 0, n);
};
// Returns everything but the last entry of the array. Especially useful on
@@ -402,10 +414,10 @@
// values in the array. The **guard** check allows it to work with `_.map`.
_.last = function(array, n, guard) {
if (array == null) return void 0;
- if ((n != null) && !guard) {
- return slice.call(array, Math.max(array.length - n, 0));
- } else {
+ if ((n == null) || guard) {
return array[array.length - 1];
+ } else {
+ return slice.call(array, Math.max(array.length - n, 0));
}
};
@@ -424,6 +436,9 @@
// Internal implementation of a recursive `flatten` function.
var flatten = function(input, shallow, output) {
+ if (shallow && _.every(input, _.isArray)) {
+ return concat.apply(output, input);
+ }
each(input, function(value) {
if (_.isArray(value) || _.isArguments(value)) {
shallow ? push.apply(output, value) : flatten(value, shallow, output);
@@ -434,7 +449,7 @@
return output;
};
- // Return a completely flattened version of an array.
+ // Flatten out an array, either recursively (by default), or just one level.
_.flatten = function(array, shallow) {
return flatten(array, shallow, []);
};
@@ -492,20 +507,10 @@
// Zip together multiple lists into a single array -- elements that share
// an index go together.
_.zip = function() {
- return _.unzip(slice.call(arguments));
- };
-
- // The inverse operation to `_.zip`. If given an array of pairs it
- // returns an array of the paired elements split into two left and
- // right element arrays, if given an array of triples it returns a
- // three element array and so on. For example, `_.unzip` given
- // `[['a',1],['b',2],['c',3]]` returns the array
- // [['a','b','c'],[1,2,3]].
- _.unzip = function(list) {
- var length = _.max(_.pluck(list, "length").concat(0));
+ var length = _.max(_.pluck(arguments, "length").concat(0));
var results = new Array(length);
for (var i = 0; i < length; i++) {
- results[i] = _.pluck(list, '' + i);
+ results[i] = _.pluck(arguments, '' + i);
}
return results;
};
@@ -516,7 +521,7 @@
_.object = function(list, values) {
if (list == null) return {};
var result = {};
- for (var i = 0, l = list.length; i < l; i++) {
+ for (var i = 0, length = list.length; i < length; i++) {
if (values) {
result[list[i]] = values[i];
} else {
@@ -534,17 +539,17 @@
// for **isSorted** to use binary search.
_.indexOf = function(array, item, isSorted) {
if (array == null) return -1;
- var i = 0, l = array.length;
+ var i = 0, length = array.length;
if (isSorted) {
if (typeof isSorted == 'number') {
- i = (isSorted < 0 ? Math.max(0, l + isSorted) : isSorted);
+ i = (isSorted < 0 ? Math.max(0, length + isSorted) : isSorted);
} else {
i = _.sortedIndex(array, item);
return array[i] === item ? i : -1;
}
}
if (nativeIndexOf && array.indexOf === nativeIndexOf) return array.indexOf(item, isSorted);
- for (; i < l; i++) if (array[i] === item) return i;
+ for (; i < length; i++) if (array[i] === item) return i;
return -1;
};
@@ -570,11 +575,11 @@
}
step = arguments[2] || 1;
- var len = Math.max(Math.ceil((stop - start) / step), 0);
+ var length = Math.max(Math.ceil((stop - start) / step), 0);
var idx = 0;
- var range = new Array(len);
+ var range = new Array(length);
- while(idx < len) {
+ while(idx < length) {
range[idx++] = start;
start += step;
}
@@ -649,19 +654,23 @@
};
// Returns a function, that, when invoked, will only be triggered at most once
- // during a given window of time.
- _.throttle = function(func, wait, immediate) {
+ // during a given window of time. Normally, the throttled function will run
+ // as much as it can, without ever going more than once per `wait` duration;
+ // but if you'd like to disable the execution on the leading edge, pass
+ // `{leading: false}`. To disable execution on the trailing edge, ditto.
+ _.throttle = function(func, wait, options) {
var context, args, result;
var timeout = null;
var previous = 0;
+ options || (options = {});
var later = function() {
- previous = new Date;
+ previous = options.leading === false ? 0 : new Date;
timeout = null;
result = func.apply(context, args);
};
return function() {
var now = new Date;
- if (!previous && immediate === false) previous = now;
+ if (!previous && options.leading === false) previous = now;
var remaining = wait - (now - previous);
context = this;
args = arguments;
@@ -670,7 +679,7 @@
timeout = null;
previous = now;
result = func.apply(context, args);
- } else if (!timeout) {
+ } else if (!timeout && options.trailing !== false) {
timeout = setTimeout(later, remaining);
}
return result;
@@ -682,17 +691,24 @@
// N milliseconds. If `immediate` is passed, trigger the function on the
// leading edge, instead of the trailing.
_.debounce = function(func, wait, immediate) {
- var result;
- var timeout = null;
+ var timeout, args, context, timestamp, result;
return function() {
- var context = this, args = arguments;
+ context = this;
+ args = arguments;
+ timestamp = new Date();
var later = function() {
- timeout = null;
- if (!immediate) result = func.apply(context, args);
+ var last = (new Date()) - timestamp;
+ if (last < wait) {
+ timeout = setTimeout(later, wait - last);
+ } else {
+ timeout = null;
+ if (!immediate) result = func.apply(context, args);
+ }
};
var callNow = immediate && !timeout;
- clearTimeout(timeout);
- timeout = setTimeout(later, wait);
+ if (!timeout) {
+ timeout = setTimeout(later, wait);
+ }
if (callNow) result = func.apply(context, args);
return result;
};
@@ -737,7 +753,6 @@
// Returns a function that will only be executed after being called N times.
_.after = function(times, func) {
- if (times <= 0) return func();
return function() {
if (--times < 1) {
return func.apply(this, arguments);
@@ -759,22 +774,33 @@
// Retrieve the values of an object's properties.
_.values = function(obj) {
- var values = [];
- for (var key in obj) if (_.has(obj, key)) values.push(obj[key]);
+ var keys = _.keys(obj);
+ var length = keys.length;
+ var values = new Array(length);
+ for (var i = 0; i < length; i++) {
+ values[i] = obj[keys[i]];
+ }
return values;
};
// Convert an object into a list of `[key, value]` pairs.
_.pairs = function(obj) {
- var pairs = [];
- for (var key in obj) if (_.has(obj, key)) pairs.push([key, obj[key]]);
+ var keys = _.keys(obj);
+ var length = keys.length;
+ var pairs = new Array(length);
+ for (var i = 0; i < length; i++) {
+ pairs[i] = [keys[i], obj[keys[i]]];
+ }
return pairs;
};
// Invert the keys and values of an object. The values must be serializable.
_.invert = function(obj) {
var result = {};
- for (var key in obj) if (_.has(obj, key)) result[obj[key]] = key;
+ var keys = _.keys(obj);
+ for (var i = 0, length = keys.length; i < length; i++) {
+ result[obj[keys[i]]] = keys[i];
+ }
return result;
};
@@ -891,6 +917,13 @@
// unique nested structures.
if (aStack[length] == a) return bStack[length] == b;
}
+ // Objects with different constructors are not equivalent, but `Object`s
+ // from different frames are.
+ var aCtor = a.constructor, bCtor = b.constructor;
+ if (aCtor !== bCtor && !(_.isFunction(aCtor) && (aCtor instanceof aCtor) &&
+ _.isFunction(bCtor) && (bCtor instanceof bCtor))) {
+ return false;
+ }
// Add the first object to the stack of traversed objects.
aStack.push(a);
bStack.push(b);
@@ -907,13 +940,6 @@
}
}
} else {
- // Objects with different constructors are not equivalent, but `Object`s
- // from different frames are.
- var aCtor = a.constructor, bCtor = b.constructor;
- if (aCtor !== bCtor && !(_.isFunction(aCtor) && (aCtor instanceof aCtor) &&
- _.isFunction(bCtor) && (bCtor instanceof bCtor))) {
- return false;
- }
// Deep compare objects.
for (var key in a) {
if (_.has(a, key)) {
@@ -1058,8 +1084,7 @@
'<': '&lt;',
'>': '&gt;',
'"': '&quot;',
- "'": '&#x27;',
- '/': '&#x2F;'
+ "'": '&#x27;'
}
};
entityMap.unescape = _.invert(entityMap.escape);
@@ -1090,7 +1115,7 @@
// Add your own custom functions to the Underscore object.
_.mixin = function(obj) {
- each(_.functions(obj), function(name){
+ each(_.functions(obj), function(name) {
var func = _[name] = obj[name];
_.prototype[name] = function() {
var args = [this._wrapped];
View
673 src/underscore.string.inc
@@ -0,0 +1,673 @@
+// Underscore.string
+// (c) 2010 Esa-Matti Suuronen
+// Underscore.string is freely distributable under the terms of the MIT license.
+// Documentation: https://github.com/epeli/underscore.string
+// Some code is borrowed from MooTools and Alexandru Marasteanu.
+// Version '2.3.2'
+
+!function(root, String){
+ 'use strict';
+
+ // Defining helper functions.
+
+ var nativeTrim = String.prototype.trim;
+ var nativeTrimRight = String.prototype.trimRight;
+ var nativeTrimLeft = String.prototype.trimLeft;
+
+ var parseNumber = function(source) { return source * 1 || 0; };
+
+ var strRepeat = function(str, qty){
+ if (qty < 1) return '';
+ var result = '';
+ while (qty > 0) {
+ if (qty & 1) result += str;
+ qty >>= 1, str += str;
+ }
+ return result;
+ };
+
+ var slice = [].slice;
+
+ var defaultToWhiteSpace = function(characters) {
+ if (characters == null)
+ return '\\s';
+ else if (characters.source)
+ return characters.source;
+ else
+ return '[' + _s.escapeRegExp(characters) + ']';
+ };
+
+ // Helper for toBoolean
+ function boolMatch(s, matchers) {
+ var i, matcher, down = s.toLowerCase();
+ matchers = [].concat(matchers);
+ for (i = 0; i < matchers.length; i += 1) {
+ matcher = matchers[i];
+ if (!matcher) continue;
+ if (matcher.test && matcher.test(s)) return true;
+ if (matcher.toLowerCase() === down) return true;
+ }
+ }
+
+ var escapeChars = {
+ lt: '<',
+ gt: '>',
+ quot: '"',
+ amp: '&',
+ apos: "'"
+ };
+
+ var reversedEscapeChars = {};
+ for(var key in escapeChars) reversedEscapeChars[escapeChars[key]] = key;
+ reversedEscapeChars["'"] = '#39';
+
+ // sprintf() for JavaScript 0.7-beta1
+ // http://www.diveintojavascript.com/projects/javascript-sprintf
+ //
+ // Copyright (c) Alexandru Marasteanu
+ // All rights reserved.
+
+ var sprintf = (function() {
+ function get_type(variable) {
+ return Object.prototype.toString.call(variable).slice(8, -1).toLowerCase();
+ }
+
+ var str_repeat = strRepeat;
+
+ var str_format = function() {
+ if (!str_format.cache.hasOwnProperty(arguments[0])) {
+ str_format.cache[arguments[0]] = str_format.parse(arguments[0]);
+ }
+ return str_format.format.call(null, str_format.cache[arguments[0]], arguments);
+ };
+
+ str_format.format = function(parse_tree, argv) {
+ var cursor = 1, tree_length = parse_tree.length, node_type = '', arg, output = [], i, k, match, pad, pad_character, pad_length;
+ for (i = 0; i < tree_length; i++) {
+ node_type = get_type(parse_tree[i]);
+ if (node_type === 'string') {
+ output.push(parse_tree[i]);
+ }
+ else if (node_type === 'array') {
+ match = parse_tree[i]; // convenience purposes only
+ if (match[2]) { // keyword argument
+ arg = argv[cursor];
+ for (k = 0; k < match[2].length; k++) {
+ if (!arg.hasOwnProperty(match[2][k])) {
+ throw new Error(sprintf('[_.sprintf] property "%s" does not exist', match[2][k]));
+ }
+ arg = arg[match[2][k]];
+ }
+ } else if (match[1]) { // positional argument (explicit)
+ arg = argv[match[1]];
+ }
+ else { // positional argument (implicit)
+ arg = argv[cursor++];
+ }
+
+ if (/[^s]/.test(match[8]) && (get_type(arg) != 'number')) {
+ throw new Error(sprintf('[_.sprintf] expecting number but found %s', get_type(arg)));
+ }
+ switch (match[8]) {
+ case 'b': arg = arg.toString(2); break;
+ case 'c': arg = String.fromCharCode(arg); break;
+ case 'd': arg = parseInt(arg, 10); break;
+ case 'e': arg = match[7] ? arg.toExponential(match[7]) : arg.toExponential(); break;
+ case 'f': arg = match[7] ? parseFloat(arg).toFixed(match[7]) : parseFloat(arg); break;
+ case 'o': arg = arg.toString(8); break;
+ case 's': arg = ((arg = String(arg)) && match[7] ? arg.substring(0, match[7]) : arg); break;
+ case 'u': arg = Math.abs(arg); break;
+ case 'x': arg = arg.toString(16); break;
+ case 'X': arg = arg.toString(16).toUpperCase(); break;
+ }
+ arg = (/[def]/.test(match[8]) && match[3] && arg >= 0 ? '+'+ arg : arg);
+ pad_character = match[4] ? ( match[4] == '0' ? '0' : match[4].charAt(1) ) : ' ';
+ pad_length = match[6] - String(arg).length;
+ pad = match[6] ? str_repeat(pad_character, pad_length) : '';
+ output.push(match[5] ? arg + pad : pad + arg);
+ }
+ }
+ return output.join('');
+ };
+
+ str_format.cache = {};
+
+ str_format.parse = function(fmt) {
+ var _fmt = fmt, match = [], parse_tree = [], arg_names = 0;
+ while (_fmt) {
+ if ((match = /^[^\x25]+/.exec(_fmt)) !== null) {
+ parse_tree.push(match[0]);
+ }
+ else if ((match = /^\x25{2}/.exec(_fmt)) !== null) {
+ parse_tree.push('%');
+ }
+ else if ((match = /^\x25(?:([1-9]\d*)\$|\(([^\)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fosuxX])/.exec(_fmt)) !== null) {
+ if (match[2]) {
+ arg_names |= 1;
+ var field_list = [], replacement_field = match[2], field_match = [];
+ if ((field_match = /^([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) {
+ field_list.push(field_match[1]);
+ while ((replacement_field = replacement_field.substring(field_match[0].length)) !== '') {
+ if ((field_match = /^\.([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) {
+ field_list.push(field_match[1]);
+ }
+ else if ((field_match = /^\[(\d+)\]/.exec(replacement_field)) !== null) {
+ field_list.push(field_match[1]);
+ }
+ else {
+ throw new Error('[_.sprintf] huh?');
+ }
+ }
+ }
+ else {
+ throw new Error('[_.sprintf] huh?');
+ }
+ match[2] = field_list;
+ }
+ else {
+ arg_names |= 2;
+ }
+ if (arg_names === 3) {
+ throw new Error('[_.sprintf] mixing positional and named placeholders is not (yet) supported');
+ }
+ parse_tree.push(match);
+ }
+ else {
+ throw new Error('[_.sprintf] huh?');
+ }
+ _fmt = _fmt.substring(match[0].length);
+ }
+ return parse_tree;
+ };
+
+ return str_format;
+ })();
+
+
+
+ // Defining underscore.string
+
+ var _s = {
+
+ VERSION: '2.3.0',
+
+ isBlank: function(str){
+ if (str == null) str = '';
+ return (/^\s*$/).test(str);
+ },
+
+ stripTags: function(str){
+ if (str == null) return '';
+ return String(str).replace(/<\/?[^>]+>/g, '');
+ },
+
+ capitalize : function(str){
+ str = str == null ? '' : String(str);
+ return str.charAt(0).toUpperCase() + str.slice(1);
+ },
+
+ chop: function(str, step){
+ if (str == null) return [];
+ str = String(str);
+ step = ~~step;
+ return step > 0 ? str.match(new RegExp('.{1,' + step + '}', 'g')) : [str];
+ },
+
+ clean: function(str){
+ return _s.strip(str).replace(/\s+/g, ' ');
+ },
+
+ count: function(str, substr){
+ if (str == null || substr == null) return 0;
+
+ str = String(str);
+ substr = String(substr);
+
+ var count = 0,
+ pos = 0,
+ length = substr.length;
+
+ while (true) {
+ pos = str.indexOf(substr, pos);
+ if (pos === -1) break;
+ count++;
+ pos += length;
+ }
+
+ return count;
+ },
+
+ chars: function(str) {
+ if (str == null) return [];
+ return String(str).split('');
+ },
+
+ swapCase: function(str) {
+ if (str == null) return '';
+ return String(str).replace(/\S/g, function(c){
+ return c === c.toUpperCase() ? c.toLowerCase() : c.toUpperCase();
+ });
+ },
+
+ escapeHTML: function(str) {
+ if (str == null) return '';
+ return String(str).replace(/[&<>"']/g, function(m){ return '&' + reversedEscapeChars[m] + ';'; });
+ },
+
+ unescapeHTML: function(str) {
+ if (str == null) return '';
+ return String(str).replace(/\&([^;]+);/g, function(entity, entityCode){
+ var match;
+
+ if (entityCode in escapeChars) {
+ return escapeChars[entityCode];
+ } else if (match = entityCode.match(/^#x([\da-fA-F]+)$/)) {
+ return String.fromCharCode(parseInt(match[1], 16));
+ } else if (match = entityCode.match(/^#(\d+)$/)) {
+ return String.fromCharCode(~~match[1]);
+ } else {
+ return entity;
+ }
+ });
+ },
+
+ escapeRegExp: function(str){
+ if (str == null) return '';
+ return String(str).replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1');
+ },
+
+ splice: function(str, i, howmany, substr){
+ var arr = _s.chars(str);
+ arr.splice(~~i, ~~howmany, substr);
+ return arr.join('');
+ },
+
+ insert: function(str, i, substr){
+ return _s.splice(str, i, 0, substr);
+ },
+
+ include: function(str, needle){
+ if (needle === '') return true;
+ if (str == null) return false;
+ return String(str).indexOf(needle) !== -1;
+ },
+
+ join: function() {
+ var args = slice.call(arguments),
+ separator = args.shift();
+
+ if (separator == null) separator = '';
+
+ return args.join(separator);
+ },
+
+ lines: function(str) {
+ if (str == null) return [];
+ return String(str).split("\n");
+ },
+
+ reverse: function(str){
+ return _s.chars(str).reverse().join('');
+ },
+
+ startsWith: function(str, starts){
+ if (starts === '') return true;
+ if (str == null || starts == null) return false;
+ str = String(str); starts = String(starts);
+ return str.length >= starts.length && str.slice(0, starts.length) === starts;
+ },
+
+ endsWith: function(str, ends){
+ if (ends === '') return true;
+ if (str == null || ends == null) return false;
+ str = String(str); ends = String(ends);
+ return str.length >= ends.length && str.slice(str.length - ends.length) === ends;
+ },
+
+ succ: function(str){
+ if (str == null) return '';
+ str = String(str);
+ return str.slice(0, -1) + String.fromCharCode(str.charCodeAt(str.length-1) + 1);
+ },
+
+ titleize: function(str){
+ if (str == null) return '';
+ str = String(str).toLowerCase();
+ return str.replace(/(?:^|\s|-)\S/g, function(c){ return c.toUpperCase(); });
+ },
+
+ camelize: function(str){
+ return _s.trim(str).replace(/[-_\s]+(.)?/g, function(match, c){ return c ? c.toUpperCase() : ""; });
+ },
+
+ underscored: function(str){
+ return _s.trim(str).replace(/([a-z\d])([A-Z]+)/g, '$1_$2').replace(/[-\s]+/g, '_').toLowerCase();
+ },
+
+ dasherize: function(str){
+ return _s.trim(str).replace(/([A-Z])/g, '-$1').replace(/[-_\s]+/g, '-').toLowerCase();
+ },
+
+ classify: function(str){
+ return _s.titleize(String(str).replace(/[\W_]/g, ' ')).replace(/\s/g, '');
+ },
+
+ humanize: function(str){
+ return _s.capitalize(_s.underscored(str).replace(/_id$/,'').replace(/_/g, ' '));
+ },
+
+ trim: function(str, characters){
+ if (str == null) return '';
+ if (!characters && nativeTrim) return nativeTrim.call(str);
+ characters = defaultToWhiteSpace(characters);
+ return String(str).replace(new RegExp('\^' + characters + '+|' + characters + '+$', 'g'), '');
+ },
+
+ ltrim: function(str, characters){
+ if (str == null) return '';
+ if (!characters && nativeTrimLeft) return nativeTrimLeft.call(str);
+ characters = defaultToWhiteSpace(characters);
+ return String(str).replace(new RegExp('^' + characters + '+'), '');
+ },
+
+ rtrim: function(str, characters){
+ if (str == null) return '';
+ if (!characters && nativeTrimRight) return nativeTrimRight.call(str);
+ characters = defaultToWhiteSpace(characters);
+ return String(str).replace(new RegExp(characters + '+$'), '');
+ },
+
+ truncate: function(str, length, truncateStr){
+ if (str == null) return '';
+ str = String(str); truncateStr = truncateStr || '...';
+ length = ~~length;
+ return str.length > length ? str.slice(0, length) + truncateStr : str;
+ },
+
+ /**
+ * _s.prune: a more elegant version of truncate
+ * prune extra chars, never leaving a half-chopped word.
+ * @author github.com/rwz
+ */
+ prune: function(str, length, pruneStr){
+ if (str == null) return '';
+
+ str = String(str); length = ~~length;
+ pruneStr = pruneStr != null ? String(pruneStr) : '...';
+
+ if (str.length <= length) return str;
+
+ var tmpl = function(c){ return c.toUpperCase() !== c.toLowerCase() ? 'A' : ' '; },
+ template = str.slice(0, length+1).replace(/.(?=\W*\w*$)/g, tmpl); // 'Hello, world' -> 'HellAA AAAAA'
+
+ if (template.slice(template.length-2).match(/\w\w/))
+ template = template.replace(/\s*\S+$/, '');
+ else
+ template = _s.rtrim(template.slice(0, template.length-1));
+
+ return (template+pruneStr).length > str.length ? str : str.slice(0, template.length)+pruneStr;
+ },
+
+ words: function(str, delimiter) {
+ if (_s.isBlank(str)) return [];
+ return _s.trim(str, delimiter).split(delimiter || /\s+/);
+ },
+
+ pad: function(str, length, padStr, type) {
+ str = str == null ? '' : String(str);
+ length = ~~length;
+
+ var padlen = 0;
+
+ if (!padStr)
+ padStr = ' ';
+ else if (padStr.length > 1)
+ padStr = padStr.charAt(0);
+
+ switch(type) {
+ case 'right':
+ padlen = length - str.length;
+ return str + strRepeat(padStr, padlen);
+ case 'both':
+ padlen = length - str.length;
+ return strRepeat(padStr, Math.ceil(padlen/2)) + str
+ + strRepeat(padStr, Math.floor(padlen/2));
+ default: // 'left'
+ padlen = length - str.length;
+ return strRepeat(padStr, padlen) + str;
+ }
+ },
+
+ lpad: function(str, length, padStr) {
+ return _s.pad(str, length, padStr);
+ },
+
+ rpad: function(str, length, padStr) {
+ return _s.pad(str, length, padStr, 'right');
+ },
+
+ lrpad: function(str, length, padStr) {
+ return _s.pad(str, length, padStr, 'both');
+ },
+
+ sprintf: sprintf,
+
+ vsprintf: function(fmt, argv){
+ argv.unshift(fmt);
+ return sprintf.apply(null, argv);
+ },
+
+ toNumber: function(str, decimals) {
+ if (!str) return 0;
+ str = _s.trim(str);
+ if (!str.match(/^-?\d+(?:\.\d+)?$/)) return NaN;
+ return parseNumber(parseNumber(str).toFixed(~~decimals));
+ },
+
+ numberFormat : function(number, dec, dsep, tsep) {
+ if (isNaN(number) || number == null) return '';
+
+ number = number.toFixed(~~dec);
+ tsep = typeof tsep == 'string' ? tsep : ',';
+
+ var parts = number.split('.'), fnums = parts[0],
+ decimals = parts[1] ? (dsep || '.') + parts[1] : '';
+
+ return fnums.replace(/(\d)(?=(?:\d{3})+$)/g, '$1' + tsep) + decimals;
+ },
+
+ strRight: function(str, sep){
+ if (str == null) return '';
+ str = String(str); sep = sep != null ? String(sep) : sep;
+ var pos = !sep ? -1 : str.indexOf(sep);
+ return ~pos ? str.slice(pos+sep.length, str.length) : str;
+ },
+
+ strRightBack: function(str, sep){
+ if (str == null) return '';
+ str = String(str); sep = sep != null ? String(sep) : sep;
+ var pos = !sep ? -1 : str.lastIndexOf(sep);
+ return ~pos ? str.slice(pos+sep.length, str.length) : str;
+ },
+
+ strLeft: function(str, sep){
+ if (str == null) return '';
+ str = String(str); sep = sep != null ? String(sep) : sep;
+ var pos = !sep ? -1 : str.indexOf(sep);
+ return ~pos ? str.slice(0, pos) : str;
+ },
+
+ strLeftBack: function(str, sep){
+ if (str == null) return '';
+ str += ''; sep = sep != null ? ''+sep : sep;
+ var pos = str.lastIndexOf(sep);
+ return ~pos ? str.slice(0, pos) : str;
+ },
+
+ toSentence: function(array, separator, lastSeparator, serial) {
+ separator = separator || ', ';
+ lastSeparator = lastSeparator || ' and ';
+ var a = array.slice(), lastMember = a.pop();
+
+ if (array.length > 2 && serial) lastSeparator = _s.rtrim(separator) + lastSeparator;
+
+ return a.length ? a.join(separator) + lastSeparator + lastMember : lastMember;
+ },
+
+ toSentenceSerial: function() {
+ var args = slice.call(arguments);
+ args[3] = true;
+ return _s.toSentence.apply(_s, args);
+ },
+
+ slugify: function(str) {
+ if (str == null) return '';
+
+ var from = "ąàáäâãåæăćęèéëêìíïîłńòóöôõøśșțùúüûñçżź",
+ to = "aaaaaaaaaceeeeeiiiilnoooooosstuuuunczz",
+ regex = new RegExp(defaultToWhiteSpace(from), 'g');
+
+ str = String(str).toLowerCase().replace(regex, function(c){
+ var index = from.indexOf(c);
+ return to.charAt(index) || '-';
+ });
+
+ return _s.dasherize(str.replace(/[^\w\s-]/g, ''));
+ },
+
+ surround: function(str, wrapper) {
+ return [wrapper, str, wrapper].join('');
+ },
+
+ quote: function(str, quoteChar) {
+ return _s.surround(str, quoteChar || '"');
+ },
+
+ unquote: function(str, quoteChar) {
+ quoteChar = quoteChar || '"';
+ if (str[0] === quoteChar && str[str.length-1] === quoteChar)
+ return str.slice(1,str.length-1);
+ else return str;
+ },
+
+ exports: function() {
+ var result = {};
+
+ for (var prop in this) {
+ if (!this.hasOwnProperty(prop) || prop.match(/^(?:include|contains|reverse)$/)) continue;
+ result[prop] = this[prop];
+ }
+
+ return result;
+ },
+
+ repeat: function(str, qty, separator){
+ if (str == null) return '';
+
+ qty = ~~qty;
+
+ // using faster implementation if separator is not needed;
+ if (separator == null) return strRepeat(String(str), qty);
+
+ // this one is about 300x slower in Google Chrome
+ for (var repeat = []; qty > 0; repeat[--qty] = str) {}
+ return repeat.join(separator);
+ },
+
+ naturalCmp: function(str1, str2){
+ if (str1 == str2) return 0;
+ if (!str1) return -1;
+ if (!str2) return 1;
+
+ var cmpRegex = /(\.\d+)|(\d+)|(\D+)/g,
+ tokens1 = String(str1).toLowerCase().match(cmpRegex),
+ tokens2 = String(str2).toLowerCase().match(cmpRegex),
+ count = Math.min(tokens1.length, tokens2.length);
+
+ for(var i = 0; i < count; i++) {
+ var a = tokens1[i], b = tokens2[i];
+
+ if (a !== b){
+ var num1 = parseInt(a, 10);
+ if (!isNaN(num1)){
+ var num2 = parseInt(b, 10);
+ if (!isNaN(num2) && num1 - num2)
+ return num1 - num2;
+ }
+ return a < b ? -1 : 1;
+ }
+ }
+
+ if (tokens1.length === tokens2.length)
+ return tokens1.length - tokens2.length;
+
+ return str1 < str2 ? -1 : 1;
+ },
+
+ levenshtein: function(str1, str2) {
+ if (str1 == null && str2 == null) return 0;
+ if (str1 == null) return String(str2).length;
+ if (str2 == null) return String(str1).length;
+
+ str1 = String(str1); str2 = String(str2);
+
+ var current = [], prev, value;
+
+ for (var i = 0; i <= str2.length; i++)
+ for (var j = 0; j <= str1.length; j++) {
+ if (i && j)
+ if (str1.charAt(j - 1) === str2.charAt(i - 1))
+ value = prev;
+ else
+ value = Math.min(current[j], current[j - 1], prev) + 1;
+ else
+ value = i + j;
+
+ prev = current[j];
+ current[j] = value;
+ }
+
+ return current.pop();
+ },
+
+ toBoolean: function(str, trueValues, falseValues) {
+ if (typeof str === "number") str = "" + str;
+ if (typeof str !== "string") return !!str;
+ str = _s.trim(str);
+ if (boolMatch(str, trueValues || ["true", "1"])) return true;
+ if (boolMatch(str, falseValues || ["false", "0"])) return false;
+ }
+ };
+
+ // Aliases
+
+ _s.strip = _s.trim;
+ _s.lstrip = _s.ltrim;
+ _s.rstrip = _s.rtrim;
+ _s.center = _s.lrpad;
+ _s.rjust = _s.lpad;
+ _s.ljust = _s.rpad;
+ _s.contains = _s.include;
+ _s.q = _s.quote;
+ _s.toBool = _s.toBoolean;
+
+ // Exporting
+
+ // CommonJS module is defined
+ if (typeof exports !== 'undefined') {
+ if (typeof module !== 'undefined' && module.exports)
+ module.exports = _s;
+
+ exports._s = _s;
+ }
+
+ // Register as a named module with AMD.
+ if (typeof define === 'function' && define.amd)
+ define('underscore.string', [], function(){ return _s; });
+
+
+ // Integrate with Underscore.js if defined
+ // or create our own underscore object.
+ root._ = root._ || {};
+ root._.string = root._.str = _s;
+}(this, String);
View
397 src/リサイズ.jsx
@@ -1 +1,396 @@
-/*===================================================================================================
+/*===================================================================================================
+ File Name: リサイズ.jsx
+ Title: リサイズ
+ Version: 1.1.0
+ Author: show555
+ Description: 選択したフォルダ内の画像を指定した長辺のサイズでリサイズする
+ Includes: Underscore.js,
+ Underscore.string.js
+===================================================================================================*/
+
+#target photoshop
+
+// Photoshopの設定単位を保存
+var originalRulerUnits = app.preferences.rulerUnits;
+// Photoshopの設定単位をピクセルに変更
+app.preferences.rulerUnits = Units.PIXELS;
+
+// 初期設定
+var settings = {
+ folderPath: '', // 対象フォルダのパスの初期値
+ _fileTypes: {
+ init: [ 'JPG' ], // 対象ファイルタイプのデフォルトチェック JPG/GIF/PNG/EPS/TIFF/BMP
+ regex: {
+ JPG: '\\.jpe?g',
+ GIF: '\\.gif',
+ PNG: '\\.png',
+ EPS: '\\.eps',
+ TIFF: '\\.tiff?',
+ BMP: '\\.bmp',
+ }
+ },
+ colorMode: 'RGB', // カラーモードの初期値
+ maxpx: 600, // 長辺のサイズの初期値
+ _quality: {
+ jpgWeb: {
+ init: 90, // 保存画質(Web用JPG)の初期値
+ min: 0,
+ max: 100
+ },
+ jpgDtp: {
+ init: 10, // 保存画質(DTP用JPG)の初期値
+ min: 0,
+ max: 12
+ },
+ },
+ doNotEnlarge: false, // 画像の長辺が指定サイズ以下の場合拡大しないの初期値
+ save: {
+ init: 'JPG', // 保存形式の初期値
+ type: {
+ jpgWeb: { label: 'JPG(WEB用)', extension: 'jpg' },
+ jpgDtp: { label: 'JPG', extension: 'jpg' },
+ eps: { label: 'EPS', extension: 'eps' },
+ png: { label: 'PNG', extension: 'png' }
+ },
+ dir: 'resize' // 保存先のディレクトリ名
+ },
+ fileTypes: [],
+ saveType: '',
+ quality: '',
+ folderObj: {}
+};
+
+// ----------------------------------▼ Underscore.js ▼----------------------------------
+#include "underscore.inc"
+#include "underscore.string.inc"
+_.mixin(_.string.exports());
+// ----------------------------------▲ Underscore.js ▲----------------------------------
+
+// 保存関数
+var saveFunctions = {
+ jpgWeb: function( theDoc, newFile, settings ) {
+ var jpegOpt = new ExportOptionsSaveForWeb();
+ jpegOpt.format = SaveDocumentType.JPEG;
+ jpegOpt.optimized = true;
+ jpegOpt.quality = settings.quality;
+ theDoc.exportDocument( newFile, ExportType.SAVEFORWEB, jpegOpt );
+ },
+ jpgDtp: function( theDoc, newFile, settings ) {
+ var jpegOpt = new JPEGSaveOptions();
+ jpegOpt.quality = settings.quality;
+ theDoc.saveAs( newFile, jpegOpt, true, Extension.LOWERCASE );
+ },
+ eps: function( theDoc, newFile, settings ) {
+ var epsOpt = new EPSSaveOptions();
+ epsOpt.embedColorProfile = true;
+ epsOpt.encoding = SaveEncoding.JPEGMAXIMUM;
+ epsOpt.halftoneScreen = false;
+ epsOpt.interpolation = false;
+ epsOpt.preview = Preview.MACOSEIGHTBIT;
+ epsOpt.psColorManagement = false;
+ epsOpt.transferFunction = false;
+ epsOpt.transparentWhites = false;
+ epsOpt.vectorData = false;
+ theDoc.saveAs( newFile, epsOpt, true, Extension.LOWERCASE );
+ },
+ png: function( theDoc, newFile, settings ) {
+ var pngOpt = new PNGSaveOptions();
+ pngOpt.interlaced = false;
+ theDoc.saveAs( newFile, pngOpt, true, Extension.LOWERCASE );
+ }
+};
+
+// 実行フラグ
+var do_flag = true;
+
+// ---------------------------------- ダイアログ作成 ----------------------------------
+// ダイアログオブジェクト
+var uDlg = new Window( 'dialog', 'リサイズ', { x:0, y:0, width:400, height:380 } );
+
+// ダイアログを画面に対して中央揃えに
+uDlg.center();
+
+// パネル 対象フォルダ
+uDlg.folderPnl = uDlg.add( "panel", { x:10, y:10, width:380, height:60 }, "対象フォルダ" );
+uDlg.folderPnl.path = uDlg.add( "edittext", { x:25, y:30, width:270, height:25 }, settings.folderPath );
+uDlg.folderPnl.selectBtn = uDlg.add( "button", { x:300, y:30, width:75, height:25 }, "選択" );
+// 対象フォルダ選択ボタンが押された時の処理
+uDlg.folderPnl.selectBtn.onClick = function() {
+ var oldPath = uDlg.folderPnl.path.text;
+ uDlg.folderPnl.path.text = Folder.selectDialog( 'フォルダを選択してください' ) || oldPath;
+}
+
+// パネル 対象ファイルタイプ
+uDlg.fileTypePnl = uDlg.add( "panel", { x:10, y:80, width:380, height:60 }, "対象ファイルタイプ" );
+uDlg.fileTypePnl.ext = [];
+uDlg.fileTypePnl.ext.push( uDlg.add( "checkbox", { x:25, y:100, width:50, height:25 }, "JPG" ) );
+uDlg.fileTypePnl.ext.push( uDlg.add( "checkbox", { x:85, y:100, width:50, height:25 }, "GIF" ) );
+uDlg.fileTypePnl.ext.push( uDlg.add( "checkbox", { x:145, y:100, width:50, height:25 }, "PNG" ) );
+uDlg.fileTypePnl.ext.push( uDlg.add( "checkbox", { x:205, y:100, width:50, height:25 }, "EPS" ) );
+uDlg.fileTypePnl.ext.push( uDlg.add( "checkbox", { x:265, y:100, width:50, height:25 }, "TIFF" ) );
+uDlg.fileTypePnl.ext.push( uDlg.add( "checkbox", { x:325, y:100, width:50, height:25 }, "BMP" ) );
+_.each( uDlg.fileTypePnl.ext, function( item, key ) {
+ if ( _.contains( settings._fileTypes.init, item.text ) ) {
+ item.value = true;
+ }
+} );
+
+// パネル 書き出し設定
+var saveTypeList = _.pluck( settings.save.type, 'label' );
+uDlg.resizePnl = uDlg.add( "panel", { x:10, y:150, width:380, height:180 }, "書き出し設定" );
+uDlg.resizePnl.colorModeText = uDlg.add( "statictext", { x:25, y:175, width:70, height:20 }, "モード:" );
+uDlg.resizePnl.saveTypeText = uDlg.add( "statictext", { x:25, y:205, width:70, height:20 }, "保存形式:" );
+uDlg.resizePnl.saveType = uDlg.add( "dropdownlist", { x:105, y:203, width:110, height:22 }, saveTypeList );
+uDlg.resizePnl.maxpxText = uDlg.add( "statictext", { x:25, y:235, width:70, height:20 }, "長辺の長さ:" );
+uDlg.resizePnl.maxpx = uDlg.add( "edittext", { x:105, y:233, width:50, height:22 }, settings.maxpx );
+uDlg.resizePnl.unitText = uDlg.add( "statictext", { x:160, y:235, width:20, height:20 }, "px" );
+uDlg.resizePnl.qualityText = uDlg.add( "statictext", { x:25, y:265, width:70, height:20 }, "画質:" );
+uDlg.resizePnl.quality = uDlg.add( "edittext", { x:105, y:263, width:50, height:22 }, settings._quality.jpgDtp.init );
+uDlg.resizePnl.qualityRange = uDlg.add( "statictext", { x:160, y:265, width:60, height:20 }, "(0〜" + settings._quality.jpgDtp.max + ")" );
+uDlg.resizePnl.qualitySlider = uDlg.add( "slider", { x:215, y:260, width:160, height:20 }, settings._quality.jpgDtp.init, settings._quality.jpgDtp.min, settings._quality.jpgDtp.max );
+uDlg.resizePnl.doNotEnlarge = uDlg.add( "checkbox", { x:25, y:293, width:350, height:20 }, "画像の長辺が指定サイズ以下の場合拡大しない" );
+uDlg.resizePnl.colorModeText.justify = uDlg.resizePnl.saveTypeText.justify = uDlg.resizePnl.maxpxText.justify = uDlg.resizePnl.qualityText.justify = 'right';
+// カラーモード選択ラジオボタンの追加
+uDlg.resizePnl.colorMode = uDlg.add( "group", { x:105, y:175, width:245, height:20 } );
+uDlg.resizePnl.colorMode.RGB = uDlg.resizePnl.colorMode.add( "radiobutton", { x:0, y:0, width:50, height:20 }, "RGB" );
+uDlg.resizePnl.colorMode.CMYK = uDlg.resizePnl.colorMode.add( "radiobutton", { x:55, y:0, width:70, height:20 }, "CMYK" );
+// カラーモードの初期値を設定
+uDlg.resizePnl.colorMode[settings.colorMode].value = true;
+// “画像の長辺が指定サイズ以下の場合拡大しない”チェックボックスの初期値を設定
+uDlg.resizePnl.doNotEnlarge.value = settings.doNotEnlarge;
+
+// 保存形式の初期値を設定
+uDlg.resizePnl.saveType.selection = _.indexOf( saveTypeList, settings.save.init );
+setSaveTypeQuality( settings.save.init );
+// 保存形式が変更された時の処理
+uDlg.resizePnl.saveType.onChange = function() {
+ setSaveTypeQuality( uDlg.resizePnl.saveType.selection.text );
+}
+// 画質のスライダーを動かしている時の処理
+uDlg.resizePnl.qualitySlider.onChanging = function() {
+ uDlg.resizePnl.quality.text = parseInt( uDlg.resizePnl.qualitySlider.value );
+}
+// 画質を入力した時の処理
+uDlg.resizePnl.quality.onChange = function() {
+ uDlg.resizePnl.qualitySlider.value = parseInt( uDlg.resizePnl.quality.text );
+}
+
+// キャンセルボタン
+uDlg.cancelBtn = uDlg.add( "button", { x:95, y:340, width:100, height:25 }, "キャンセル", { name: "cancel" } );
+// キャンセルボタンが押されたらキャンセル処理(ESCキー含む)
+uDlg.cancelBtn.onClick = function() {
+ // 実行フラグにfalseを代入
+ do_flag = false;
+ // ダイアログを閉じる
+ uDlg.close();
+}
+
+// OKボタン
+uDlg.okBtn = uDlg.add( "button", { x:205, y:340, width:100, height:25 }, "リサイズ実行", { name: "ok" } );
+// OKボタンが押されたら各設定項目に不備がないかチェック
+uDlg.okBtn.onClick = function() {
+ // 各種項目の値を格納
+ settings.folderPath = uDlg.folderPnl.path.text;
+ settings.folderObj = new Folder( settings.folderPath );
+ settings.colorMode = uDlg.resizePnl.colorMode.RGB.value ? 'RGB' : 'CMYK';
+ settings.saveType = getSaveTypeKey( uDlg.resizePnl.saveType.selection.text );
+ settings.maxpx = parseInt( uDlg.resizePnl.maxpx.text );
+ settings.doNotEnlarge = uDlg.resizePnl.doNotEnlarge.value;
+ settings.fileTypes = [];
+ _.each( uDlg.fileTypePnl.ext, function( item ) {
+ if ( item.value ) {
+ settings.fileTypes.push( item.text );
+ }
+ } );
+
+ // 対象フォルダが選択されているかチェック
+ if ( !settings.folderPath ) {
+ alert( '対象フォルダが選択されていません' );
+ return false;
+ }
+ // 対象フォルダが存在するかチェック
+ if ( !settings.folderObj.exists ) {
+ alert( '対象フォルダが存在しません' );
+ return false;
+ }
+ // 拡張子が最低1つは選択されているかチェック
+ if ( settings.fileTypes.length < 1 ) {
+ alert( '対象ファイルタイプが選択されていません' );
+ return false;
+ }
+ // カラーモードがCMYKの時保存形式がPNGになっていないかチェック
+ if ( settings.colorMode == 'CMYK' ) {
+ if ( settings.saveType == 'jpgWeb' ) {
+ alert( 'JPG(WEB用)形式で保存するためにはカラーモードはRGBでなければいけません' );
+ return false;
+ }
+ if ( settings.saveType == 'png' ) {
+ alert( 'PNG形式で保存するためにはカラーモードはRGBでなければいけません' );
+ return false;
+ }
+ }
+ // 長辺の長さが入力されているかチェック
+ if ( _.isNaN( settings.maxpx ) ) {
+ alert( '長辺の長さを整数で入力して下さい' );
+ return false;
+ }
+ // 長辺の長さが0より大きいかチェック
+ if ( settings.maxpx < 1 ) {
+ alert( '0より大きい長辺の長さを入力しください' );
+ return false;
+ }
+ // 保存形式がJPG/JPG(WEB用)の場合
+ if ( _.contains( [ 'jpgWeb', 'jpgDtp' ], settings.saveType ) ) {
+ // 画質が入力されているかチェック
+ settings.quality = parseInt( uDlg.resizePnl.quality.text );
+ if ( _.isNaN( settings.quality ) ) {
+ alert( '画質を整数で入力して下さい' );
+ return false;
+ }
+ }
+ // 不備がなかった場合処理続行
+ uDlg.close();
+}
+
+// ダイアログ表示
+uDlg.show();
+
+// ---------------------------------- メインリサイズ処理 ----------------------------------
+if ( do_flag ) {
+ // alert( 'フォルダ:' + uDlg.folderPnl.path.text + "\n" + '拡張子:' + settings.fileTypes.join( ', ' ) + "\n" + 'モード:' + settings.colorMode + "\n" + '保存形式:' + settings.saveType + "\n" + '長辺のサイズ:' + settings.maxpx + "\n" + '画質:' + settings.quality + "\n" + '画像が小さい場合拡大しない:' + settings.doNotEnlarge );
+
+ // 複数の対象ファイルを取得するための正規表現オブジェクトを作成
+ var extensions = [];
+ _.each( settings.fileTypes, function( fileType ) {
+ extensions.push( settings._fileTypes.regex[fileType] );
+ } );
+ var fileReg = new RegExp( '(' + extensions.join( '|' ) + ')$', 'i' );
+ // 対象ファイルを取得
+ var files = settings.folderObj.getFiles( function( thefile ) {
+ if ( fileReg.test( thefile.name ) ) {
+ return true;
+ } else {
+ return false;
+ }
+ } );
+
+ // 進捗バーを表示
+ var ProgressPanel = CreateProgressPanel( files.length, 500, '処理中…', true );
+ ProgressPanel.show();
+ var i = 1;
+
+ // 対象ファイルに対してリサイズ→保存のループ処理
+ _.each( files, function( file ) {
+ // キャンセルの場合処理中止
+ if ( !do_flag ) return;
+ // 進捗バーを更新
+ ProgressPanel.val( i );
+ // ファイルオープン
+ var theDoc = app.open( file );
+ // カラーモードをRGBに変更
+ theDoc.changeMode( ChangeMode[settings.colorMode] );
+ //リサイズする
+ var w = theDoc.width.value;
+ var h = theDoc.height.value;
+ if ( w > h && judgeResizeable( w, h ) ) {
+ theDoc.resizeImage( settings.maxpx, h * ( settings.maxpx/w ), 72, ResampleMethod.BICUBICSHARPER );
+ } else if ( h >= w && judgeResizeable( w, h ) ) {
+ theDoc.resizeImage( w * ( settings.maxpx/h ), settings.maxpx, 72, ResampleMethod.BICUBICSHARPER );
+ }
+ // 保存先フォルダを作成
+ var saveDir = new Folder( theDoc.path + '/' + settings.save.dir );
+ if( !saveDir.exists ){
+ saveDir.create();
+ }
+ // 保存用の新規オブジェクト作成
+ var newFile = new File( theDoc.path + '/' + settings.save.dir + '/' + theDoc.name.replace( /\.\w+$/i, '' ) + '.' + settings.save.type[settings.saveType].extension );
+ // 保存形式ごとの関数を呼び出し
+ saveFunctions[settings.saveType]( theDoc, newFile, settings );
+ // ファイルクローズ
+ theDoc.close( SaveOptions.DONOTSAVECHANGES );
+
+ i++;
+ } );
+}
+if ( ProgressPanel ) {
+ ProgressPanel.close();
+}
+
+// Photoshopの設定単位を復元
+app.preferences.rulerUnits = originalRulerUnits;
+
+// ------------------------------------------ 関数 -----------------------------------------
+function setSaveTypeQuality( saveType ) {
+ var key = getSaveTypeKey( saveType );
+ if ( _.contains( [ 'jpgWeb', 'jpgDtp' ], key ) ) {
+ uDlg.resizePnl.quality.text = settings._quality[key].init;
+ uDlg.resizePnl.qualityRange.text = "(" + settings._quality[key].min + "" + settings._quality[key].max + ")";
+ uDlg.resizePnl.qualitySlider.minvalue = settings._quality[key].min;
+ uDlg.resizePnl.qualitySlider.maxvalue = settings._quality[key].max;
+ uDlg.resizePnl.qualitySlider.value = settings._quality[key].init;
+ uDlg.resizePnl.qualityText.enabled = true;
+ uDlg.resizePnl.qualityRange.enabled = true;
+ uDlg.resizePnl.quality.enabled = true;
+ uDlg.resizePnl.qualitySlider.enabled = true;
+ } else {
+ uDlg.resizePnl.qualityText.enabled = false;
+ uDlg.resizePnl.qualityRange.enabled = false;
+ uDlg.resizePnl.quality.enabled = false;
+ uDlg.resizePnl.qualitySlider.enabled = false;
+ }
+}
+
+function getSaveTypeKey( saveType ) {
+ var saveTypeKey;
+ _.some( settings.save.type, function( value, key ) {
+ if ( value.label == saveType ) {
+ saveTypeKey = key;
+ return true;
+ }
+ return false;
+ } );
+ return saveTypeKey;
+}
+
+function judgeResizeable( w, h ) {
+ if ( w > settings.maxpx || h > settings.maxpx ) {
+ return true;
+ }
+ if ( w < settings.maxpx && h < settings.maxpx && !settings.doNotEnlarge ) {
+ return true;
+ }
+ return false;
+}
+
+function CreateProgressPanel( myMaximumValue, myProgressBarWidth , progresTitle, useCancel ) {
+ var progresTitle = typeof progresTitle == 'string' ? progresTitle : 'Processing...';
+ myProgressPanel = new Window( 'palette', _.sprintf( "%s(%d/%d)", progresTitle, 1, myMaximumValue ) );
+ myProgressPanel.myProgressBar = myProgressPanel.add( 'progressbar', [ 12, 12, myProgressBarWidth, 24 ], 0, myMaximumValue );
+ if ( useCancel ) {
+ myProgressPanel.cancel = myProgressPanel.add( 'button', undefined, 'キャンセル' );
+ myProgressPanel.cancel.onClick = function() {
+ try {
+ do_flag = false;
+ myProgressPanel.close();
+ } catch(e) {
+ alert(e);
+ }
+ }
+ }
+ var PP = {
+ 'ProgressPanel': myProgressPanel,
+ 'title': progresTitle,
+ 'show': function() { this.ProgressPanel.show() },
+ 'close': function() { this.ProgressPanel.close() },
+ 'max': myMaximumValue,
+ 'barwidth': myProgressBarWidth,
+ 'val': function( val ) {
+ this.ProgressPanel.myProgressBar.value = val;
+ if ( val < this.max ) {
+ this.ProgressPanel.text = _.sprintf( "%s(%d/%d)", this.title, val+1, this.max );
+ }
+ this.ProgressPanel.update();
+ }
+ }
+ return PP;
+}
View
2,346 リサイズ.jsx
2,345 additions, 1 deletion not shown

No commit comments for this range

Something went wrong with that request. Please try again.