【问题标题】:How to re-size an image and preview it before uploading如何在上传前调整图像大小并进行预览
【发布时间】:2013-02-15 18:19:13
【问题描述】:

我有一个 input->type->file 按钮,允许用户上传图片。 我正在尝试在他们提交(上传)图像之前预览图像。谁能帮我解决,我如何重新调整图像大小(在单击提交之前)以适合 div(用于预览)。

css

#preview_box{
    margin-top:10px;
    margin-left:10px;
    float:left;
    display:inline;
    text-align:center;
    height:408px;
    width:490px;
    position:relative;
    border: 1px solid #adadad; /* stroke */
    background-color: #fff; /* layer fill content */
    -moz-box-shadow: 0 1px 6px rgba(0,0,0,.22); /* drop shadow */
    -webkit-box-shadow: 0 1px 6px rgba(0,0,0,.22); /* drop shadow */
    box-shadow: 0 1px 6px rgba(0,0,0,.22); /* drop shadow */
}

html

<div id="preview_box">This is a preview</div>

<form id="imageform" enctype="multipart/form-data" method="post" action="/help/upload.php">                     
      <input name="photoimg" id="photoimg" type="file"/>
</form>

jquery

$("input[name='photoimg']").on("change", function(){
  var files = !!this.files ? this.files : [];
  // If no files were selected, or no FileReader support, return
  if ( !files.length || !window.FileReader ) return;
  // Only proceed if the selected file is an image
 if ( /^image/.test( files[0].type ) ) { 
  // Create a new instance of the FileReader
    reader = new FileReader();
   // Read the local file as a DataURL
    reader.readAsDataURL( files[0] );
   // When loaded, set image data as background of page
     reader.onloadend = function(){
    $("#preview_box").css("background-image", "url(" + this.result + ")");
      }
   }
});

谢谢。 (如果我可以在调整图像大小时保持纵横比,那就太好了)

【问题讨论】:

    标签: javascript file-upload image-resizing preview aspect-ratio


    【解决方案1】:

    ...上传前预览

    可以在大多数浏览器的最新版本中完成。见:

    is it possible to preview local images before uploading them via a form?

    但是,为了向后兼容,我建议您通过 ajax 上传图像并在单独的对话框中执行图像大小调整 + 裁剪。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-11
      • 1970-01-01
      • 2015-06-19
      • 2015-08-06
      相关资源
      最近更新 更多