function
sliceCurrentDocument() {
var
doc = activeDocument;
if
(!doc) {
alert(
"没有打开的文档!"
);
return
;
}
var
mainFolder =
new
Folder($.fileName).parent;
var
outputFolder =
new
Folder(mainFolder.fsName +
"/输出文件夹"
);
if
(!outputFolder.exists) {
if
(!outputFolder.create()) {
alert(
"无法创建输出文件夹: "
+ outputFolder.fsName);
return
;
}
}
var
psdName = doc.name.replace(
'.psd'
,
''
);
var
psdOutputFolder =
new
Folder(outputFolder.fsName +
"/"
+ psdName);
if
(!psdOutputFolder.exists) {
if
(!psdOutputFolder.create()) {
alert(
"无法创建PSD输出文件夹: "
+ psdOutputFolder.fsName);
return
;
}
}
var
exportFormat =
"JPG"
;
sliceAndSave(doc, psdOutputFolder, psdName, exportFormat);
alert(
"处理完成!"
);
}
function
sliceAndSave(doc, targetFolder, baseFileName, exportFormat) {
var
horizontalGuides = [0];
var
verticalGuides = [0];
var
sliceIndex = 0;
for
(
var
i = 0; i < doc.guides.length; i++) {
if
(doc.guides[i].direction.typename ===
"Direction.HORIZONTAL"
) {
horizontalGuides.push(doc.guides[i].coordinate);
}
else
{
verticalGuides.push(doc.guides[i].coordinate);
}
}
var
historyState = activeDocument.activeHistoryState;
for
(
var
y = 0; y < horizontalGuides.length; y++) {
var
bottom = (y < horizontalGuides.length - 1) ? horizontalGuides[y + 1] : doc.height;
for
(
var
x = 0; x < verticalGuides.length; x++) {
sliceIndex++;
var
right = (x < verticalGuides.length - 1) ? verticalGuides[x + 1] : doc.width;
doc.crop([verticalGuides[x], horizontalGuides[y], right, bottom]);
var
fileName = baseFileName +
"-"
+ sliceIndex +
"."
+ exportFormat.toLowerCase();
var
file =
new
File(targetFolder.fsName +
"/"
+ fileName);
if
(exportFormat ===
"JPG"
) {
var
jpgSaveOptions =
new
JPEGSaveOptions();
jpgSaveOptions.quality = 10;
doc.saveAs(file, jpgSaveOptions,
true
, Extension.LOWERCASE);
}
else
if
(exportFormat ===
"PNG"
) {
var
pngSaveOptions =
new
PNGSaveOptions();
pngSaveOptions.compression = 0;
doc.saveAs(file, pngSaveOptions,
true
, Extension.LOWERCASE);
}
else
if
(exportFormat ===
"PSD"
) {
var
psdSaveOptions =
new
PhotoshopSaveOptions();
doc.saveAs(file, psdSaveOptions,
true
, Extension.LOWERCASE);
}
activeDocument.activeHistoryState = historyState;
}
}
}
sliceCurrentDocument();