草庐IT

php - Jcrop 对大尺寸图像有问题

coder 2024-04-09 原文

由谷歌翻译

我正在运行以在 php 和 jquery 中实现一个上传表单,并说现在一切都很好,除了一件事我认为是无稽之谈但仍然无法弄清楚。 让我解释: 在实践中,当我运行图像上传时,我立即打印到屏幕上的是一个临时预览,我将在那里剪切成我喜欢的图像,然后保存缩略图。然而,这个预览,如果我插入 jpg 高分辨率我看到真人大小,对页面来说太大了。代码如下:

索引.PHP

<?php
function uploadImageFile() { // Note: GD library is required for this function
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $iWidth = $iHeight = 100; // desired image result dimensions
    $iJpgQuality = 90;

    if ($_FILES) {

        // if no errors and size less than 250kb
        if (! $_FILES['image_file']['error'] && $_FILES['image_file']['size'] < 55555250 * 1024) {
            if (is_uploaded_file($_FILES['image_file']['tmp_name'])) {

                // new unique filename
                $sTempFileName = 'cache/' . md5(time().rand());

                // move uploaded file into cache folder
                move_uploaded_file($_FILES['image_file']['tmp_name'], $sTempFileName);

                // change file permission to 644
                @chmod($sTempFileName, 0644);

                if (file_exists($sTempFileName) && filesize($sTempFileName) > 0) {
                    $aSize = getimagesize($sTempFileName); // try to obtain image info
                    if (!$aSize) {
                        @unlink($sTempFileName);
                        return;
                    }

                    // check for image type
                    switch($aSize[2]) {
                        case IMAGETYPE_JPEG:
                            $sExt = '.jpg';

                            // create a new image from file 
                            $vImg = @imagecreatefromjpeg($sTempFileName);
                            break;
                        /*case IMAGETYPE_GIF:
                            $sExt = '.gif';

                            // create a new image from file 
                            $vImg = @imagecreatefromgif($sTempFileName);
                            break;*/
                        case IMAGETYPE_PNG:
                            $sExt = '.png';

                            // create a new image from file 
                            $vImg = @imagecreatefrompng($sTempFileName);
                            break;
                        default:
                            @unlink($sTempFileName);
                            return;
                    }

                    // create a new true color image
                    $vDstImg = @imagecreatetruecolor( $iWidth, $iHeight );

                    // copy and resize part of an image with resampling
                    imagecopyresampled($vDstImg, $vImg, 0, 0, (int)$_POST['x1'], (int)$_POST['y1'], $iWidth, $iHeight, (int)$_POST['w'], (int)$_POST['h']);

                    // define a result image filename
                    $sResultFileName = $sTempFileName . $sExt;

                    // output image to file
                    imagejpeg($vDstImg, $sResultFileName, $iJpgQuality);
                    @unlink($sTempFileName);

                    return $sResultFileName;

                }
            }
        }
    }
}
}

$sImage = uploadImageFile();
echo '<div align=center><img src="'.$sImage.'" /></div>';
echo $sImage;
?>
  <!-- add styles -->
    <link href="css/main.css" rel="stylesheet" type="text/css" />
    <link href="css/jquery.Jcrop.min.css" rel="stylesheet" type="text/css" />

    <!-- add scripts -->
    <script src="js/jquery.min.js"></script>
    <script src="js/jquery.Jcrop.min.js"></script>
    <script src="js/script.js"></script>
</head>
<body>

    <div class="demo">
        <div class="bbody">

            <!-- upload form -->
            <form id="upload_form" enctype="multipart/form-data" method="post" onsubmit="return checkForm()">
                <!-- hidden crop params -->
                <input type="hidden" id="x1" name="x1" />
                <input type="hidden" id="y1" name="y1" />
                <input type="hidden" id="x2" name="x2" />
                <input type="hidden" id="y2" name="y2" />

                <h2>Step1: Please select image file</h2>
                <div><input type="file" name="image_file" id="image_file" onchange="fileSelectHandler()" /></div>

                <div class="error"></div>

                <div class="step2">
                    <h2>Step2: Please select a crop region</h2>
                    <img id="preview"/> <!-- QUESTA È LA PREVIEW -->

                    <div class="info">
                        <label>File size</label> <input type="text" id="filesize" name="filesize" />
                        <label>Type</label> <input type="text" id="filetype" name="filetype" />
                        <label>Image dimension</label> <input type="text" id="filedim" name="filedim" />
                        <label>W</label> <input type="text" id="w" name="w" />
                        <label>H</label> <input type="text" id="h" name="h" />
                    </div>

                    <input type="submit" value="Upload" />
                </div>
            </form>
        </div>
    </div>
</body>
</html>

脚本.JS

function bytesToSize(bytes) {
var sizes = ['Bytes', 'KB', 'MB'];
if (bytes == 0) return 'n/a';
var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
return (bytes / Math.pow(1024, i)).toFixed(1) + ' ' + sizes[i];
};

// check for selected crop region
function checkForm() {
  if (parseInt($('#w').val())) return true;
  $('.error').html('Please select a crop region and then press Upload').show();
  return false;
};

// update info by cropping (onChange and onSelect events handler)
function updateInfo(e) {
$('#x1').val(e.x);
$('#y1').val(e.y);
$('#x2').val(e.x2);
$('#y2').val(e.y2);
$('#w').val(e.w);
$('#h').val(e.h);
};

// clear info by cropping (onRelease event handler)
function clearInfo() {
$('.info #w').val('');
$('.info #h').val('');
};

function fileSelectHandler() {

// get selected file
var oFile = $('#image_file')[0].files[0];

// hide all errors
$('.error').hide();

// check for image type (jpg and png are allowed)
var rFilter = /^(image\/jpeg|image\/png)$/i;
if (! rFilter.test(oFile.type)) {
    $('.error').html('Please select a valid image file (jpg and png are allowed)').show();
    return;
}

// check for file size
if (oFile.size > 55555250 * 1024) {
    $('.error').html('You have selected too big file, please select a one smaller image file').show();
    return;
}

// preview element
var oImage = document.getElementById('preview');

// prepare HTML5 FileReader
var oReader = new FileReader();
    oReader.onload = function(e) {

    // e.target.result contains the DataURL which we can use as a source of the image
    oImage.src = e.target.result;
    oImage.onload = function () { // onload event handler

        // display step 2
        $('.step2').fadeIn(500);

        // display some basic image info
        var sResultFileSize = bytesToSize(oFile.size);
        $('#filesize').val(sResultFileSize);
        $('#filetype').val(oFile.type);
        $('#filedim').val(oImage.naturalWidth + ' x ' + oImage.naturalHeight);

        // Create variables (in this scope) to hold the Jcrop API and image size
        var jcrop_api, boundx, boundy;

        // destroy Jcrop if it is existed
        if (typeof jcrop_api != 'undefined') 
            jcrop_api.destroy();

        // initialize Jcrop
        $('#preview').Jcrop({
            minSize: [32, 32], // min crop size
            aspectRatio : 1, // keep aspect ratio 1:1
            bgFade: true, // use fade effect
            bgOpacity: .3, // fade opacity
            onChange: updateInfo,
            onSelect: updateInfo,
            onRelease: clearInfo
        }, function(){

            // use the Jcrop API to get the real image size
            var bounds = this.getBounds();
            boundx = bounds[0];
            boundy = bounds[1];

            // Store the Jcrop API in the jcrop_api variable
            jcrop_api = this;
        });
    };
};

// read selected file as DataURL
oReader.readAsDataURL(oFile);
}

jquey.Jcrop.min.css

/* jquery.Jcrop.min.css v0.9.10 (build:20120429) */
.jcrop-holder{direction:ltr;text-align:left;}
.jcrop-vline,.jcrop-hline{background:#FFF url(Jcrop.gif) top left repeat;font-size:0;position:absolute;}
.jcrop-vline{height:100%;width:1px!important;}
.jcrop-hline{height:1px!important;width:100%;}
.jcrop-vline.right{right:0;}
.jcrop-hline.bottom{bottom:0;}
.jcrop-handle{background-color:#333;border:1px #eee solid;font-size:1px;}
.jcrop-tracker{-webkit-tap-highlight-color:transparent;-webkit-touch-callout:none;-webkit-user-select:none;height:100%;width:100%;}
.jcrop-handle.ord-n{left:50%;margin-left:-4px;margin-top:-4px;top:0;}
.jcrop-handle.ord-s{bottom:0;left:50%;margin-bottom:-4px;margin-left:-4px;}
.jcrop-handle.ord-e{margin-right:-4px;margin-top:-4px;right:0;top:50%;}
.jcrop-handle.ord-w{left:0;margin-left:-4px;margin-top:-4px;top:50%;}
.jcrop-handle.ord-nw{left:0;margin-left:-4px;margin-top:-4px;top:0;}
.jcrop-handle.ord-ne{margin-right:-4px;margin-top:-4px;right:0;top:0;}
.jcrop-handle.ord-se{bottom:0;margin-bottom:-4px;margin-right:-4px;right:0;}
.jcrop-handle.ord-sw{bottom:0;left:0;margin-bottom:-4px;margin-left:-4px;}
.jcrop-dragbar.ord-n,.jcrop-dragbar.ord-s{height:7px;width:100%;}
.jcrop-dragbar.ord-e,.jcrop-dragbar.ord-w{height:100%;width:7px;}
.jcrop-dragbar.ord-n{margin-top:-4px;}
.jcrop-dragbar.ord-s{bottom:0;margin-bottom:-4px;}
.jcrop-dragbar.ord-e{margin-right:-4px;right:0;}
.jcrop-dragbar.ord-w{margin-left:-4px;}
.jcrop-light .jcrop-vline,.jcrop-light .jcrop-hline{background:#FFF;filter:Alpha(opacity=70)!important;opacity:.70!important;}
.jcrop-light .jcrop-handle{-moz-border-radius:3px;-webkit-border-radius:3px;background-color:#000;border-color:#FFF;border-radius:3px;}
.jcrop-dark .jcrop-vline,.jcrop-dark .jcrop-hline{background:#000;filter:Alpha(opacity=70)!important;opacity:.7!important;}
.jcrop-dark .jcrop-handle{-moz-border-radius:3px;-webkit-border-radius:3px;background-color:#FFF;border-color:#000;border-radius:3px;}
.jcrop-holder img,img.jcrop-preview{max-width:none;}

如果不明白你可以下载完整的脚本。 (对不起我的英语,我是意大利人) 下载:http://dfiles.eu/files/6yazp1des

最佳答案

回复晚了,但希望将来能帮助其他人处理 JCrop 中的较大图像。您无需做任何更大的事情,只需像这样提供 JCrop 的参数

 $('#cropbox').Jcrop({
      aspectRatio: 1,  //If you want to keep aspectRatio
      boxWidth: 650,   //Maximum width you want for your bigger images
      boxHeight: 400,  //Maximum Height for your bigger images
      onSelect: updateCoords 
 },function()
 {
      alert('Now you see smaller preview of your bigger one.');
 });

好消息是,当您裁剪图像并获取尺寸时,您将获得真实图像尺寸,即大图像的尺寸,因此您可以通过服务器裁剪图像而无需再次计算任何内容,只需发送尺寸和裁剪即可。

关于php - Jcrop 对大尺寸图像有问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15889625/

有关php - Jcrop 对大尺寸图像有问题的更多相关文章

  1. ruby - 在 64 位 Snow Leopard 上使用 rvm、postgres 9.0、ruby 1.9.2-p136 安装 pg gem 时出现问题 - 2

    我想为Heroku构建一个Rails3应用程序。他们使用Postgres作为他们的数据库,所以我通过MacPorts安装了postgres9.0。现在我需要一个postgresgem并且共识是出于性能原因你想要pggem。但是我对我得到的错误感到非常困惑当我尝试在rvm下通过geminstall安装pg时。我已经非常明确地指定了所有postgres目录的位置可以找到但仍然无法完成安装:$envARCHFLAGS='-archx86_64'geminstallpg--\--with-pg-config=/opt/local/var/db/postgresql90/defaultdb/po

  2. ruby - 通过 rvm 升级 ruby​​gems 的问题 - 2

    尝试通过RVM将RubyGems升级到版本1.8.10并出现此错误:$rvmrubygemslatestRemovingoldRubygemsfiles...Installingrubygems-1.8.10forruby-1.9.2-p180...ERROR:Errorrunning'GEM_PATH="/Users/foo/.rvm/gems/ruby-1.9.2-p180:/Users/foo/.rvm/gems/ruby-1.9.2-p180@global:/Users/foo/.rvm/gems/ruby-1.9.2-p180:/Users/foo/.rvm/gems/rub

  3. ruby - 通过 RVM (OSX Mountain Lion) 安装 Ruby 2.0.0-p247 时遇到问题 - 2

    我的最终目标是安装当前版本的RubyonRails。我在OSXMountainLion上运行。到目前为止,这是我的过程:已安装的RVM$\curl-Lhttps://get.rvm.io|bash-sstable检查已知(我假设已批准)安装$rvmlistknown我看到当前的稳定版本可用[ruby-]2.0.0[-p247]输入命令安装$rvminstall2.0.0-p247注意:我也试过这些安装命令$rvminstallruby-2.0.0-p247$rvminstallruby=2.0.0-p247我很快就无处可去了。结果:$rvminstall2.0.0-p247Search

  4. ruby - Fast-stemmer 安装问题 - 2

    由于fast-stemmer的问题,我很难安装我想要的任何ruby​​gem。我把我得到的错误放在下面。Buildingnativeextensions.Thiscouldtakeawhile...ERROR:Errorinstallingfast-stemmer:ERROR:Failedtobuildgemnativeextension./System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/bin/rubyextconf.rbcreatingMakefilemake"DESTDIR="cleanmake"DESTDIR=

  5. ruby - 安装 Ruby 时遇到问题(无法下载资源 "readline--patch") - 2

    当我尝试安装Ruby时遇到此错误。我试过查看this和this但无济于事➜~brewinstallrubyWarning:YouareusingOSX10.12.Wedonotprovidesupportforthispre-releaseversion.Youmayencounterbuildfailuresorotherbreakages.Pleasecreatepull-requestsinsteadoffilingissues.==>Installingdependenciesforruby:readline,libyaml,makedepend==>Installingrub

  6. java - 从 JRuby 调用 Java 类的问题 - 2

    我正在尝试使用boilerpipe来自JRuby。我看过guide从JRuby调用Java,并成功地将它与另一个Java包一起使用,但无法弄清楚为什么同样的东西不能用于boilerpipe。我正在尝试基本上从JRuby中执行与此Java等效的操作:URLurl=newURL("http://www.example.com/some-location/index.html");Stringtext=ArticleExtractor.INSTANCE.getText(url);在JRuby中试过这个:require'java'url=java.net.URL.new("http://www

  7. ruby-on-rails - 简单的 Ruby on Rails 问题——如何将评论附加到用户和文章? - 2

    我意识到这可能是一个非常基本的问题,但我现在已经花了几天时间回过头来解决这个问题,但出于某种原因,Google就是没有帮助我。(我认为部分问题在于我是一个初学者,我不知道该问什么......)我也看过O'Reilly的RubyCookbook和RailsAPI,但我仍然停留在这个问题上.我找到了一些关于多态关系的信息,但它似乎不是我需要的(尽管如果我错了请告诉我)。我正在尝试调整MichaelHartl'stutorial创建一个包含用户、文章和评论的博客应用程序(不使用脚手架)。我希望评论既属于用户又属于文章。我的主要问题是:我不知道如何将当前文章的ID放入评论Controller。

  8. ruby-on-rails - 添加回形针新样式不影响旧上传的图像 - 2

    我有带有Logo图像的公司模型has_attached_file:logo我用他们的Logo创建了许多公司。现在,我需要添加新样式has_attached_file:logo,:styles=>{:small=>"30x15>",:medium=>"155x85>"}我是否应该重新上传所有旧数据以重新生成新样式?我不这么认为……或者有什么rake任务可以重新生成样式吗? 最佳答案 参见Thumbnail-Generation.如果rake任务不适合你,你应该能够在控制台中使用一个片段来调用重新处理!关于相关公司

  9. 【高数】用拉格朗日中值定理解决极限问题 - 2

    首先回顾一下拉格朗日定理的内容:函数f(x)是在闭区间[a,b]上连续、开区间(a,b)上可导的函数,那么至少存在一个,使得:通过这个表达式我们可以知道,f(x)是函数的主体,a和b可以看作是主体函数f(x)中所取的两个值。那么可以有,  也就意味着我们可以用来替换 这种替换可以用在求某些多项式差的极限中。方法: 外层函数f(x)是一致的,并且h(x)和g(x)是等价无穷小。此时,利用拉格朗日定理,将原式替换为 ,再进行求解,往往会省去复合函数求极限的很多麻烦。使用要注意:1.要先找到主体函数f(x),即外层函数必须相同。2.f(x)找到后,复合部分是等价无穷小。3.要满足作差的形式。如果是加

  10. SPI接收数据异常问题总结 - 2

    SPI接收数据左移一位问题目录SPI接收数据左移一位问题一、问题描述二、问题分析三、探究原理四、经验总结最近在工作在学习调试SPI的过程中遇到一个问题——接收数据整体向左移了一位(1bit)。SPI数据收发是数据交换,因此接收数据时从第二个字节开始才是有效数据,也就是数据整体向右移一个字节(1byte)。请教前辈之后也没有得到解决,通过在网上查阅前人经验终于解决问题,所以写一个避坑经验总结。实际背景:MCU与一款芯片使用spi通信,MCU作为主机,芯片作为从机。这款芯片采用的是它规定的六线SPI,多了两根线:RDY和INT,这样从机就可以主动请求主机给主机发送数据了。一、问题描述根据从机芯片手

随机推荐