M>>Исходники не покажу
kuj>Ну вот.
Не, частями — легко. Например (дальше — весь код взят из проекта):
<!--------------------------
VALIDATION FUNCTIONS
---------------------------->
<!---
Accepts JSON structs, NOT CF structs!!
validate("
{
fieldName : {
functionName : functionReturnValue, // if function return this value, OK
functionName : params // function must return true for OK and false for Error
}
}
")
Function returns struct:
{
FieldName : {
FuncName : Params, // FuncName : '' if no params
FuncName2 : Params
},
FieldName : {
FuncName : Params,
FuncName2 : Params
}
}
Example:
validateFields('
{
login : {
length : "4, 16",
isAscii : true,
isUniqueUser : true
},
password : {
length : "4, 16",
isAscii : true,
isEqualTo : 'repeat_password'
},
email : {
isValidEmail : true
}
}
')
Return Example (returns CF struct, not JSON!!!):
{
login : {
length : '4, 16'
},
password : {
length : '4, 16',
isAscii : ''
}
}
Return Example (everything is OK) (returns CF struct, not JSON!!!):
{}
---->
<cffunction name="validate">
<cfargument name="FieldList" required="yes" type="string">
<cfset var Errors = StructNew()>
<cfset FieldList = jsondecode(FieldList)>
<cfif NOT IsStruct(FieldList)>
<cfreturn Errors>
</cfif>
<cfset Fields = StructKeyArray(FieldList)>
<cfloop from="1" to="#ArrayLen(Fields)#" index="FieldIndex">
<cfset Field = Fields[FieldIndex]>
<cfset FuncNames = StructKeyArray(FieldList[Field])>
<cfloop from="1" to="#ArrayLen(FuncNames)#" index="FuncNameIndex">
<cfset FuncName = FuncNames[FuncNameIndex]>
<cfset Params = FieldList[Field][FuncName]>
<cftry>
<cfset Result = Evaluate('#FuncName#(ReqVar(Field), Params)')>
<cfset RequiredResponse = Params>
<cfif NOT IsBoolean(RequiredResponse)>
<cfset RequiredResponse = true>
</cfif>
<cfif RequiredResponse NEQ Result>
<cfset Errors[Field][FuncName] = Params>
</cfif>
<cfcatch type="any">
<cfset Errors[Field][FuncName] = cfcatch.Message>
</cfcatch>
</cftry>
</cfloop>
</cfloop>
<cfreturn Errors>
</cffunction>
только что это тебе даст —
ЗЫ. В сторону — возможным знатокам Coldfusion сразу отвечаю на вопрос. Почему не использовал IsCustomFunction? Да потому что я так и не смог эту глючную функцию завести. Проще (и вряд ли менее производительно) через <cftry>
Ну или вот:
#
#
# resize images and embed watermark if needed
#
# Author: Dmitrii 'Mamut' Dimandt
#
# Requires Python Imaging Library
#
# Watermark code found on the net
#
# Converts all images to JPG
#
# w - path to watermark
# t - transparency of the watermark
#
# o - path to output directory
# h - path to thumb directory
# d - path to details directory
#
# example:
#
# python image_resize.py -w "C:/home/dmitriid/Documents/w.png"
# -t 0.4
# -r 800
# -o "/home/dmitriid/Documents/images/watermarked/"
# -d "/home/dmitriid/Documents/images/watermarked/details/"
# -h "/home/dmitriid/Documents/images/watermarked/thumbs/"
# "/home/dmitriid/Documents/images/1.png"
# "/home/dmitriid/Documents/images/2.png"
# "/home/dmitriid/Documents/images/3.png"
import os
import sys
import glob
import getopt
import Image, ImageEnhance
def reduce_opacity(im, opacity):
"""Returns an image with reduced opacity."""
assert opacity >= 0 and opacity <= 1
if im.mode != 'RGBA':
im = im.convert('RGBA')
else:
im = im.copy()
alpha = im.split()[3]
alpha = ImageEnhance.Brightness(alpha).enhance(opacity)
im.putalpha(alpha)
return im
def watermark(im, mark, position, opacity=1, resize=0):
"""Adds a watermark to an image."""
if opacity < 1:
mark = reduce_opacity(mark, opacity)
if im.mode != 'RGBA':
im = im.convert('RGBA')
# create a transparent layer the size of the image and draw the
# watermark in that layer.
layer = Image.new('RGBA', im.size, (0,0,0,0))
if position == 'tile':
for y in range(0, im.size[1], mark.size[1]):
for x in range(0, im.size[0], mark.size[0]):
layer.paste(mark, (x, y))
elif position == 'scale':
# scale, but preserve the aspect ratio
ratio = min(
float(im.size[0]) / mark.size[0], float(im.size[1]) / mark.size[1])
w = int(mark.size[0] * ratio / 1.5)
h = int(mark.size[1] * ratio / 1.5)
mark = mark.resize((w, h))
layer.paste(mark, ((im.size[0] - w) / 2, (im.size[1] - h) / 2))
else:
layer.paste(mark, position)
# composite the watermark with the layer
return Image.composite(layer, im, layer)
def test():
im = Image.open('test.png')
mark = Image.open('overlay.png')
watermark(im, mark, 'tile', 0.5).show()
watermark(im, mark, 'scale', 1.0).show()
watermark(im, mark, (100, 100), 0.5).show()
if __name__ == '__main__':
opts, args = getopt.getopt(sys.argv[1:], "w:o:t:r:d:h:")
wmark = ''
output = ''
thumboutput = ''
detailsoutput = ''
transparency = 0.5
resize = 0
for o, a in opts:
if o == '-w':
wmark = a
if o == '-o':
output = a
if o == '-d':
detailsoutput = a
if o == '-h':
thumboutput = a
if o == '-t':
transparency = float(a)
if o == '-r':
resize = int(a)
for fname in args:
try:
#print '---',fname
im = Image.open(fname)
width, height = im.size
print width, height
if wmark != '':
mark = Image.open(wmark)
im = watermark(im, mark, 'scale', transparency)
im.thumbnail((800, 800), Image.ANTIALIAS)
filename, ext = os.path.splitext(os.path.basename(fname.lower()))
filename = '%s.%s'%(filename, 'jpg')
im.save(os.path.join(output, filename))
width, height = im.size
cropwidth = 0
cropheight = 0
if width > height:
cropwidth = height
cropheight = height
else:
cropwidth = width
cropheight = width
left = (width - cropwidth) / 2
right = left + cropwidth
upper = (height - cropheight) / 2
lower = upper + cropheight
thumb_image = im.crop((left, upper, right, lower))
thumb_image.load()
if detailsoutput != '':
thumb_image.thumbnail((200,200), Image.ANTIALIAS)
thumb_image.save(os.path.join(detailsoutput, filename))
if thumboutput != '':
thumb_image.thumbnail((100,100), Image.ANTIALIAS)
thumb_image.save(os.path.join(thumboutput, filename))
except:
print 'Failed'
этот питоновский код скоро будет заменен следующим (советую все программистам на Java, которые пытаются понять, как же манипулировать изображениями в Java, не особо теряя качество):
package Mamut;
import java.io.*;
import java.awt.*;
import java.awt.image.*;
import javax.imageio.*;
import javax.swing.*;
// Image utils
//
// @author Dmitrii 'Mamut' Dimandt, dmitrii <at> dmitriid.com
// @author Anatolii Faschevski, realsweb
//
//
//
// Usage:
//
// ImageUtils ui = new ImageUtils();
//
// ui.load(file);
//
// ui.thumbnail(150);
// ui.save(out_file);
// ui.reload();
// ui.crop(40, 40, 100, 130);
// ui.save(out_file2);
//
//
// ui.load(file).thumbnail(150).save(out_file)
// .reload()
// .crop(40, 40, 100, 130).resize(400, 400).save(out_file2)
//
// int width = ui.getWidth();
// int height = ui.getHeight();
public class ImageUtils
{
private Image img_out;
private BufferedImage inputImage = null,
thumbImage = null;
private Toolkit tk = Toolkit.getDefaultToolkit();
private int height = 0,
width = 0;
private String image_path = "";
public ImageUtils load(String file_path)
{
image_path = file_path;
try
{
File f = new File(image_path);
if(!f.isFile())
return this;
inputImage = toBufferedImage(tk.createImage(image_path));
thumbImage = inputImage;
width = inputImage.getWidth();
height = inputImage.getHeight();
return this;
}
catch(Exception e)
{
}
return this;
}
public ImageUtils save(String file_path)
{
return save(file_path, "JPEG");
}
public ImageUtils save(String file_path, String type)
{
try
{
File outputFile = new File(file_path);
ImageIO.write(thumbImage, type, outputFile);
} catch(IOException e)
{
}
return this;
}
public ImageUtils reload()
{
thumbImage = inputImage;
width = thumbImage.getWidth();
height = thumbImage.getHeight();
return this;
}
public int getWidth()
{
return width;
}
public int getHeight()
{
return height;
}
public ImageUtils crop(int x, int y, int w/*idth*/, int h/*eight*/)
{
if(x > width || y > height)
return this;
x = x < 0 ? 0 : x;
y = y < 0 ? 0 : y;
w = x + w > width ? width - x : w;
h = y + h > height ? height - y : h;
ImageFilter filter = new CropImageFilter(x, y, w, h);
ImageProducer prod = new FilteredImageSource(thumbImage.getSource(), filter);
img_out = tk.createImage(prod);
thumbImage = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
Graphics2D graphics2D = thumbImage.createGraphics();
graphics2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
graphics2D.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
graphics2D.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
graphics2D.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
graphics2D.drawImage(img_out, 0, 0, w, h, null);
width = thumbImage.getWidth();
height = thumbImage.getHeight();
return this;
}
public ImageUtils resize(int w, int h)
{
return resize(w, h, false);
}
public ImageUtils resize(int w, int h, boolean forceResizeUp /*scale images up?*/)
{
if(w <= 0 || h <= 0)
return this;
if(w > width && h > height && !forceResizeUp)
return this;
ImageFilter filter = new AreaAveragingScaleFilter(w, h);
ImageProducer prod = new FilteredImageSource(thumbImage.getSource(), filter);
img_out = tk.createImage(prod);
thumbImage = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
Graphics2D graphics2D = thumbImage.createGraphics();
graphics2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
graphics2D.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
graphics2D.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
graphics2D.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
graphics2D.drawImage(img_out, 0, 0, w, h, null);
width = thumbImage.getWidth();
height = thumbImage.getHeight();
return this;
}
public ImageUtils thumbnail(int edge)
{
return thumbnail(edge, false);
}
public ImageUtils thumbnail(int edge, boolean preserveRatio)
{
if(edge <= 0)
edge = height > width ? height : width;
if(!preserveRatio)
{
int w = width > height ? height : width;
int h = width > height ? height : width;
int x = width > height ? (width - height) / 2 : 0;
int y = width > height ? 0 : (height - width) / 2;
crop(x, y, w, h);
}
int edge_x, edge_y;
edge_x = edge_y = edge;
if(preserveRatio)
{
edge_x = (int) (width > height ? edge : width * (edge / (float) height));
edge_y = (int) (width > height ? height * (edge / (float) width) : edge);
}
resize(edge_x, edge_y);
return this;
}
public ImageUtils watermark(String img, int xCoord, int yCoord, int alpha)
{
float ta = (float)alpha / 100;
BufferedImage watermarkedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
BufferedImage watermark = null;
Graphics2D graphics2D = watermarkedImage.createGraphics();
graphics2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
graphics2D.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
graphics2D.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
graphics2D.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
graphics2D.drawImage(thumbImage, 0, 0, width, height, null);
boolean knowntype = false; // "Unknown file extension."
try
{
File fw = new File(img);
if (fw.isFile())
{
// file
try
{
watermark = ImageIO.read(fw);
}
catch (Exception e)
{
}
}
}
catch (Exception e)
{
}
if (watermark != null)
{
try
{
graphics2D.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, ta));
}
catch (Exception e) {
}
graphics2D.drawImage(watermark, xCoord, yCoord, inputImage.getWidth(), inputImage.getHeight(), null);
}
thumbImage = watermarkedImage;
return this;
}
// This method returns a buffered image with the contents of an image
private BufferedImage toBufferedImage(Image image) {
if (image instanceof BufferedImage) {
return (BufferedImage)image;
}
// This code ensures that all the pixels in the image are loaded
image = new ImageIcon(image).getImage();
// Determine if the image has transparent pixels; for this method's
// implementation, see e661 Determining If an Image Has Transparent Pixels
boolean hasAlpha = hasAlpha(image);
// Create a buffered image with a format that's compatible with the screen
BufferedImage bimage = null;
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
try {
// Determine the type of transparency of the new buffered image
int transparency = Transparency.OPAQUE;
if (hasAlpha) {
transparency = Transparency.BITMASK;
}
// Create the buffered image
GraphicsDevice gs = ge.getDefaultScreenDevice();
GraphicsConfiguration gc = gs.getDefaultConfiguration();
bimage = gc.createCompatibleImage(image.getWidth(null),
image.getHeight(null),
transparency);
} catch (HeadlessException e) {
// The system does not have a screen
}
if (bimage == null) {
// Create a buffered image using the default color model
int type = BufferedImage.TYPE_INT_RGB;
if (hasAlpha) {
type = BufferedImage.TYPE_INT_ARGB;
}
bimage = new BufferedImage(image.getWidth(null), image.getHeight(null), type);
}
// Copy image to buffered image
Graphics g = bimage.createGraphics();
// Paint the image onto the buffered image
g.drawImage(image, 0, 0, null);
g.dispose();
return bimage;
}
private boolean hasAlpha(Image image)
{
try {
PixelGrabber pg = new PixelGrabber(image, 0, 0, 1, 1, false);
pg.grabPixels();
return pg.getColorModel().hasAlpha();
}
catch (InterruptedException e) {
return false;
}
}
}
ну и так далее. У нас там еще РНР в одном месте применяется, но там код просто тривиальнейший
Если что надо, спрашивай
![](/Forum/Images/wink.gif)
... << RSDN@Home 1.2.0 alpha 4 rev. 1091>>
M>>Если что надо, спрашивай
WF>За catch(...) { } — бить нещадно железной линейкой. По почкам.
Есть такое
![](/Forum/Images/smile.gif)
Мотивация такая: несмотря на легкость связки Coldfusion-Java появляется куча обвязочного кода, который нафиг не нужен. А так как код нужен был позавчера, а написан только сегодня, то...
WF>У тебя же
WF>WF>ui.load(file);
WF>ui.thumbnail(150);
WF>
WF>Тупо выбросит NPE, если load не сработает.
Это можно отловить уровнем выше — в Coldfusion. Я, правда, не уверен, что мы его в try/catch оборачиваем
WF>Пакадж тоже назван неправильно
Ага. Писался с прицелом на совсем другое. Но в итоге...
![](/Forum/Images/shuffle.gif)
... << RSDN@Home 1.2.0 alpha 4 rev. 1091>>