我们曾经被几个读者问到同一个问题——如何将照片传到网上。我认为这是一个很有趣的问题,我决定在本文中解决掉这个问题。但是,我认为只是单纯的实现上传功能可能会有些单调,所以我决定添加一个很重要的元素—剪切功能。相信这样应该更有魅力的说。
html
第一步,我们先画一个表头
现在再描绘主体部分
CSS
.bheader {
background-color: #DDDDDD;
border-radius: 10px 10px 0 0;
padding: 10px 0;
text-align: center;
}
.bbody {
color: #000;
overflow: hidden;
padding-bottom: 20px;
text-align: center;
background: -moz-linear-gradient(#ffffff, #f2f2f2);
background: -ms-linear-gradient(#ffffff, #f2f2f2);
background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #ffffff), color-stop(100%, #f2f2f2));
background: -webkit-linear-gradient(#ffffff, #f2f2f2);
background: -o-linear-gradient(#ffffff, #f2f2f2);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffff', endColorstr='#f2f2f2');
-ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffff', endColorstr='#f2f2f2')";
background: linear-gradient(#ffffff, #f2f2f2);
}
.bbody h2, .info, .error {
margin: 10px 0;
}
.step2, .error {
display: none;
}
.error {
font-size: 18px;
font-weight: bold;
color: red;
}
.info {
font-size: 14px;
}
label {
margin: 0 5px;
}
input {
border: 1px solid #CCCCCC;
border-radius: 10px;
padding: 4px 8px;
text-align: center;
width: 70px;
}
.jcrop-holder {
display: inline-block;
}
input[type=submit] {
background: #e3e3e3;
border: 1px solid #bbb;
border-radius: 3px;
-webkit-box-shadow: inset 0 0 1px 1px #f6f6f6;
box-shadow: inset 0 0 1px 1px #f6f6f6;
color: #333;
font: bold 12px/1 "helvetica neue", helvetica, arial, sans-serif;
padding: 8px 0 9px;
text-align: center;
text-shadow: 0 1px 0 #fff;
width: 150px;
}
input[type=submit]:hover {
background: #d9d9d9;
-webkit-box-shadow: inset 0 0 1px 1px #eaeaea;
box-shadow: inset 0 0 1px 1px #eaeaea;
color: #222;
cursor: pointer;
}
input[type=submit]:active {
background: #d0d0d0;
-webkit-box-shadow: inset 0 0 1px 1px #e3e3e3;
box-shadow: inset 0 0 1px 1px #e3e3e3;
color: #000;
}
JS
// convert bytes into friendly format
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 > 250 * 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);
}
PHP
function uploadImageFile() { // Note: GD library is required for this function
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$iWidth = $iHeight = 200; // 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'] 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_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 '';
这样,带剪切功能的上传图片就已经完成了,若有疑问,请留言。大家共勉。

H5 및 HTML5는 동일한 것을, 즉 html5를 나타냅니다. HTML5는 HTML의 다섯 번째 버전으로 시맨틱 태그, 멀티미디어 지원, 캔버스 및 그래픽, 오프라인 스토리지 및 로컬 스토리지와 같은 새로운 기능을 제공하여 웹 페이지의 표현성 및 상호 작용성을 향상시킵니다.

h5referstohtml5, apivotaltechnologyinwebdevelopment.1) html5introducesnewelements 및 dynamicwebapplications.2) itsupp ortsmultimediawithoutplugins, enovannangeserexperienceacrossdevices.3) SemanticLementsImproveContentsTructUreAndSeo.4) H5'Srespo

H5 개발에서 마스터 해야하는 도구 및 프레임 워크에는 vue.js, React 및 Webpack이 포함됩니다. 1.vue.js는 사용자 인터페이스를 구축하고 구성 요소 개발을 지원하는 데 적합합니다. 2. 복잡한 응용 프로그램에 적합한 가상 DOM을 통해 페이지 렌더링을 최적화합니다. 3. Webpack은 모듈 포장에 사용되며 리소스로드를 최적화합니다.

html5hassignificallytransformedwebdevelopmentbyintranticalticlementements, 향상 Multimediasupport 및 Improvingperformance.1) itmadewebsitessmoreaccessibleadseo 친환경적 인 요소, 및 .2) Html5intagnatee

H5는 시맨틱 요소 및 ARIA 속성을 통해 웹 페이지 접근성 및 SEO 효과를 향상시킵니다. 1. 컨텐츠 구조를 구성하고 SEO를 개선하기 위해 사용합니다. 2. Aria-Label과 같은 ARIA 속성은 접근성을 향상시키고 보조 기술 사용자는 웹 페이지를 원활하게 사용할 수 있습니다.

"H5"와 "HTML5"는 대부분의 경우 동일하지만 특정 시나리오에서는 다른 의미를 가질 수 있습니다. "HTML5"는 새로운 태그와 API를 포함하는 W3C 정의 표준입니다. "H5"는 일반적으로 HTML5의 약어이지만 모바일 개발에서는 HTML5를 기반으로 한 프레임 워크를 참조 할 수 있습니다. 이러한 차이를 이해하면 프로젝트 에서이 용어를 정확하게 사용하는 데 도움이됩니다.

H5 또는 HTML5는 HTML의 다섯 번째 버전입니다. 개발자에게 더 강력한 도구 세트를 제공하여 복잡한 웹 애플리케이션을보다 쉽게 만들 수 있습니다. H5의 핵심 기능에는 다음이 포함됩니다. 1) 웹 페이지에 그래픽 및 애니메이션을 그리는 요소; 2) 웹 페이지 구조를 SEO 최적화에 명확하고 도움이되는 시맨틱 태그 등; 3) GeolocationApi 지원 위치 기반 서비스와 같은 새로운 API; 4) 호환성 테스트 및 폴리 필 라이브러리를 통해 크로스 브라우저 호환성을 보장해야합니다.

H5 링크를 만드는 방법? 링크 대상 결정 : H5 페이지 또는 응용 프로그램의 URL을 가져옵니다. HTML 앵커 작성 : & lt; a & gt; 태그 앵커를 만들고 링크 대상 URL을 지정합니다. 링크 속성 설정 (선택 사항) : 필요에 따라 대상, 제목 및 on 클릭 속성을 설정하십시오. 웹 페이지에 추가 : 링크가 나타나려는 웹 페이지에 HTML 앵커 코드를 추가하십시오.


핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사

뜨거운 도구

MinGW - Windows용 미니멀리스트 GNU
이 프로젝트는 osdn.net/projects/mingw로 마이그레이션되는 중입니다. 계속해서 그곳에서 우리를 팔로우할 수 있습니다. MinGW: GCC(GNU Compiler Collection)의 기본 Windows 포트로, 기본 Windows 애플리케이션을 구축하기 위한 무료 배포 가능 가져오기 라이브러리 및 헤더 파일로 C99 기능을 지원하는 MSVC 런타임에 대한 확장이 포함되어 있습니다. 모든 MinGW 소프트웨어는 64비트 Windows 플랫폼에서 실행될 수 있습니다.

WebStorm Mac 버전
유용한 JavaScript 개발 도구

SecList
SecLists는 최고의 보안 테스터의 동반자입니다. 보안 평가 시 자주 사용되는 다양한 유형의 목록을 한 곳에 모아 놓은 것입니다. SecLists는 보안 테스터에게 필요할 수 있는 모든 목록을 편리하게 제공하여 보안 테스트를 더욱 효율적이고 생산적으로 만드는 데 도움이 됩니다. 목록 유형에는 사용자 이름, 비밀번호, URL, 퍼징 페이로드, 민감한 데이터 패턴, 웹 셸 등이 포함됩니다. 테스터는 이 저장소를 새로운 테스트 시스템으로 간단히 가져올 수 있으며 필요한 모든 유형의 목록에 액세스할 수 있습니다.

Dreamweaver Mac版
시각적 웹 개발 도구

안전한 시험 브라우저
안전한 시험 브라우저는 온라인 시험을 안전하게 치르기 위한 보안 브라우저 환경입니다. 이 소프트웨어는 모든 컴퓨터를 안전한 워크스테이션으로 바꿔줍니다. 이는 모든 유틸리티에 대한 액세스를 제어하고 학생들이 승인되지 않은 리소스를 사용하는 것을 방지합니다.
