比如,上传用户头像,尺寸太大将不允许怎么限制,最好有代码。

解决方案 »

  1.   

    只做过服务端的验证,客户端的验证不知道能否实现
    参考:http://download.csdn.net/source/2874743http://download.csdn.net/source/2530273
      

  2.   

    JavaScript验证的代码
    <HTML>
    <HEAD>
    <SCRIPT>
    function getImageDimension (imgURL, loadHandler) {
     var img = new Image();
     img.onload = loadHandler;
     if (document.layers
       && location.protocol.toLowerCase() != 'file:'
       && navigator.javaEnabled())
      netscape.security.PrivilegeManager.enablePrivilege(
       'UniversalFileRead'
      );
     img.src = imgURL;
    }
    function getFileSize (fileName) {
     if (document.layers) {
      if (navigator.javaEnabled()) {
       var file = new java.io.File(fileName);
       if (location.protocol.toLowerCase() != 'file:')
        netscape.security.PrivilegeManager.enablePrivilege(
        'UniversalFileRead'
        );
       return file.length();
      }
      else return -1;
     }
     else if (document.all) {
      window.oldOnError = window.onerror;
      window.onerror = function (err) {
       if (err.indexOf('utomation') != -1) {
        alert('file access not possible');
        return true;
       }
       else
        return false;
      };
      var fso = new ActiveXObject('Scripting.FileSystemObject');
      var file = fso.GetFile(fileName);
      window.onerror = window.oldOnError;
      return file.Size;
     }
    }
    function showImageDimensions () {
     alert(this.width + 'x' + this.height);
    }
    </SCRIPT>
    <SCRIPT>
    function checkImageDimensions (fileName) {
     var imgURL = 'file:///' + fileName;
     getImageDimension(imgURL, showImageDimensions);
    }
    </SCRIPT>
    </HEAD>
    <BODY>
    <FORM NAME="formName">
    <INPUT TYPE="file" NAME="fileName">
    <BR>
    <INPUT TYPE="button" VALUE="check file size"
        ONCLICK="alert(getFileSize(this.form.fileName.value))"
    >
    <BR>
    <INPUT TYPE="button" VALUE="check image dimensions"
        ONCLICK="checkImageDimensions(this.form.fileName.value)"
    >
    </FORM>
    </BODY>
    </HTML>
      

  3.   

    相关的类似百度空间 qq空间 都有 点击ie9的 工具--->f12开发人员工具 查看源代码,当然你要是觉得查看完了打开再来检查即可
      

  4.   

    import java.awt.Color;
    import java.awt.Component;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.Image;
    import java.awt.MediaTracker;
    import java.awt.Toolkit;
    import java.awt.image.BufferedImage;
    import java.awt.image.ConvolveOp;
    import java.awt.image.Kernel;
    import java.io.ByteArrayOutputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.OutputStream;import javax.imageio.ImageIO;
    import javax.swing.ImageIcon;import com.sun.image.codec.jpeg.JPEGCodec;
    import com.sun.image.codec.jpeg.JPEGEncodeParam;
    import com.sun.image.codec.jpeg.JPEGImageEncoder;/**
     * 图像压缩工具
     * @author [email protected]
     *
     */
    public class ImageSizer {
        public static final MediaTracker tracker = new MediaTracker(new Component() {
            private static final long serialVersionUID = 1234162663955668507L;} 
        );
        /**
         * @param originalFile 原图像
         * @param resizedFile 压缩后的图像
         * @param width 图像宽
         * @param format 图片格式 jpg, png, gif(非动画)
         * @throws IOException
         */
        public static void resize(File originalFile, File resizedFile, int width, String format) throws IOException {
            if(format!=null && "gif".equals(format.toLowerCase())){
             resize(originalFile, resizedFile, width, 1);
             return;
            }
            FileInputStream fis = new FileInputStream(originalFile);
            ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
            int readLength = -1;
            int bufferSize = 1024;
            byte bytes[] = new byte[bufferSize];
            while ((readLength = fis.read(bytes, 0, bufferSize)) != -1) {
                byteStream.write(bytes, 0, readLength);
            }
            byte[] in = byteStream.toByteArray();
            fis.close();
            byteStream.close();
            
         Image inputImage = Toolkit.getDefaultToolkit().createImage( in );
            waitForImage( inputImage );
            int imageWidth = inputImage.getWidth( null );
            if ( imageWidth < 1 ) 
               throw new IllegalArgumentException( "image width " + imageWidth + " is out of range" );
            int imageHeight = inputImage.getHeight( null );
            if ( imageHeight < 1 ) 
               throw new IllegalArgumentException( "image height " + imageHeight + " is out of range" );
            
            // Create output image.
            int height = -1;
            double scaleW = (double) imageWidth / (double) width;
            double scaleY = (double) imageHeight / (double) height;
            if (scaleW >= 0 && scaleY >=0) {
                if (scaleW > scaleY) {
                    height = -1;
                } else {
                    width = -1;
                }
            }
            Image outputImage = inputImage.getScaledInstance( width, height, java.awt.Image.SCALE_DEFAULT);
            checkImage( outputImage );        
            encode(new FileOutputStream(resizedFile), outputImage, format);        
        }        /** Checks the given image for valid width and height. */
        private static void checkImage( Image image ) {
           waitForImage( image );
           int imageWidth = image.getWidth( null );
           if ( imageWidth < 1 ) 
              throw new IllegalArgumentException( "image width " + imageWidth + " is out of range" );
           int imageHeight = image.getHeight( null );
           if ( imageHeight < 1 ) 
              throw new IllegalArgumentException( "image height " + imageHeight + " is out of range" );
        }    /** Waits for given image to load. Use before querying image height/width/colors. */
        private static void waitForImage( Image image ) {
           try {
              tracker.addImage( image, 0 );
              tracker.waitForID( 0 );
              tracker.removeImage(image, 0);
           } catch( InterruptedException e ) { e.printStackTrace(); }
        }     /** Encodes the given image at the given quality to the output stream. */
        private static void encode( OutputStream outputStream, Image outputImage, String format ) 
           throws java.io.IOException {
           int outputWidth  = outputImage.getWidth( null );
           if ( outputWidth < 1 ) 
              throw new IllegalArgumentException( "output image width " + outputWidth + " is out of range" );
           int outputHeight = outputImage.getHeight( null );
           if ( outputHeight < 1 ) 
              throw new IllegalArgumentException( "output image height " + outputHeight + " is out of range" );       // Get a buffered image from the image.
           BufferedImage bi = new BufferedImage( outputWidth, outputHeight,
              BufferedImage.TYPE_INT_RGB );                                                   
           Graphics2D biContext = bi.createGraphics();
           biContext.drawImage( outputImage, 0, 0, null );
           ImageIO.write(bi, format, outputStream);
           outputStream.flush();      
        } 
        
    /**
     * 缩放gif图片
     * @param originalFile 原图片
     * @param resizedFile 缩放后的图片
     * @param newWidth 宽度
     * @param quality 缩放比例 (等比例)
     * @throws IOException
     */
        private static void resize(File originalFile, File resizedFile, int newWidth, float quality) throws IOException {
            if (quality < 0 || quality > 1) {
                throw new IllegalArgumentException("Quality has to be between 0 and 1");
            } 
            ImageIcon ii = new ImageIcon(originalFile.getCanonicalPath());
            Image i = ii.getImage();
            Image resizedImage = null; 
            int iWidth = i.getWidth(null);
            int iHeight = i.getHeight(null); 
            if (iWidth > iHeight) {
                resizedImage = i.getScaledInstance(newWidth, (newWidth * iHeight) / iWidth, Image.SCALE_SMOOTH);
            } else {
                resizedImage = i.getScaledInstance((newWidth * iWidth) / iHeight, newWidth, Image.SCALE_SMOOTH);
            } 
            // This code ensures that all the pixels in the image are loaded.
            Image temp = new ImageIcon(resizedImage).getImage(); 
            // Create the buffered image.
            BufferedImage bufferedImage = new BufferedImage(temp.getWidth(null), temp.getHeight(null),
                                                            BufferedImage.TYPE_INT_RGB); 
            // Copy image to buffered image.
            Graphics g = bufferedImage.createGraphics(); 
            // Clear background and paint the image.
            g.setColor(Color.white);
            g.fillRect(0, 0, temp.getWidth(null), temp.getHeight(null));
            g.drawImage(temp, 0, 0, null);
            g.dispose(); 
            // Soften.
            float softenFactor = 0.05f;
            float[] softenArray = {0, softenFactor, 0, softenFactor, 1-(softenFactor*4), softenFactor, 0, softenFactor, 0};
            Kernel kernel = new Kernel(3, 3, softenArray);
            ConvolveOp cOp = new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP, null);
            bufferedImage = cOp.filter(bufferedImage, null); 
            // Write the jpeg to a file.
            FileOutputStream out = new FileOutputStream(resizedFile);        
            // Encodes image as a JPEG data stream
            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out); 
            JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bufferedImage); 
            param.setQuality(quality, true); 
            encoder.setJPEGEncodeParam(param);
            encoder.encode(bufferedImage);
        }
    }可能会有点错误,楼主自己改一下
      

  5.   

    比较老的办法是上传到服务器端,在那里进行验证大小,或者做缩略图。但现在基本上使用flex或者silverlight来直接在客户端来搞。
      

  6.   

    可以用JS加Flash上传文件,你可以查找Jquery 上传文件,可以作到在客户端判断大小,
    另外,图片压缩,很少自己写程序,
    在Linxu下,可以用ImageMagick的Convert命令实现,速度快,任何格式都支持。
    功能无限。
    如果你是windows平台,可以装个cygwin+ImageMagick试试。
      

  7.   

    用到jquery了、、自己去弄一个、想要多大的自己设置就可以了! <script type="text/javascript" src="jquery.min.js"></script>
      <script type="text/javascript">
      function changePic(obj) {
            var img    = new Image();
            img.src    = obj.value;
    var width  = img.width;
            var height = img.height;
                     if(width>500||height>500){
    alert('图片太大');
    $(obj).after($(obj).clone($(obj)));
    $(obj).remove();
    }
    }
      </script>
      
    <input type="file" name="img" id="img"  onchange="changePic(this);">
      

  8.   

    再给你个后台的缩放图片package com.huang.test;import java.awt.Image;    
    import java.awt.image.BufferedImage;
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.OutputStream;
    import javax.imageio.ImageIO;
    import com.sun.image.codec.jpeg.JPEGCodec;
    import com.sun.image.codec.jpeg.JPEGImageEncoder;public class lessenImg { public static void main(String[] args) {
    File file=new File("D://1.jpg");
    try {
    Image src=ImageIO.read(file);
    BufferedImage bufferedImage=new BufferedImage(200,200,BufferedImage.TYPE_INT_RGB);
    bufferedImage.getGraphics().drawImage(src,0,0,200,200,null);//绘制缩小后的图,两个一致...
    OutputStream os=new FileOutputStream("D://aa.jpg");
    JPEGImageEncoder encoder=JPEGCodec.createJPEGEncoder(os);
    encoder.encode(bufferedImage);
    os.close();
    System.out.println("完成");
    } catch (IOException e) {
    e.printStackTrace();
    }
    }
    }有俩对宽和高、、你只需要设置成一样就可以了!!!