이미지 조정
자르기 도구로 브라우저에서 사진을 자르고 회전하고 보정한 뒤, 원본 파일과 조정 내용을 데이터로 전달하세요.
이 페이지의 내용
독자가 사진을 고르고, 자르고, 90도씩 회전하고, 밝기, 대비, 채도를 설정하면서 결과를 바로 확인합니다. 브라우저에서는 사진 자체를 바꾸지 않습니다. 페이지가 전달하는 것은 원본 파일과 데이터로 된 조정 내용이며, 저장할 사진을 자르고 인코딩하는 일은 애플리케이션의 이미지 파이프라인이 담당합니다. 이 페이지에서는 자르기 도구, 네이티브 입력 요소, CSS 필터로 이를 구현합니다.
이미지 조정
<section class="sheet p-lg container-inline" data-example="image-adjustments" aria-labelledby="adjust-title"> <div class="flex flex-wrap items-center justify-between gap-sm mb-md"> <h2 class="m(0) text-md font-medium fg-text-strong" id="adjust-title">Adjust a picture</h2> <div class="flex flex-wrap items-center gap-xs"> <label class="btn btn-sm"> <svg class="icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"> <path d="M7.5892 2.215A0.4996 0.4996 0 0 0 7.5 2.5L7.5006 10.0245A0.5 0.5 0 0 0 8.4946 10.0734L8.5 10L8.4986 2.4621A0.5007 0.5007 0 0 0 8.4108 2.215A0.7044 0.7044 0 0 0 7.5892 2.215Z" fill="currentColor" stroke="none" fill-rule="evenodd" /> <path d="M5 5.5L7.8586 2.6414A0.2 0.2 0 0 1 8.1414 2.6414L11 5.5" /> <path d="M2.5 10.5L2.5 12.5A1 1 0 0 0 3.5 13.5L12.5 13.5A1 1 0 0 0 13.5 12.5L13.5 10.5" /> </svg> <span data-choose>Choose a picture</span> <input type="file" class="sr-only" accept="image/*" aria-describedby="adjust-hint"> </label> <button type="button" class="btn btn-sm btn-quiet" data-clear disabled>Clear</button> </div> </div> <p class="m(0) mb-md text-sm fg-text-muted" id="adjust-hint">The picture stays in this browser. Nothing is uploaded.</p> <div data-error hidden> <div class="alert alert-danger mb-md" role="alert"> <div class="alert-body"> <p class="alert-description">That file could not be read as a picture. Choose a PNG, JPG, WebP or AVIF.</p> </div> </div> </div> <div class="grid gap-lg grid-cols(1) grid-cols(2)@container(--2xl)"> <div class="flex flex-col gap-sm min-w(0)"> <div class="cropper" style="--cropper-x: 0; --cropper-y: 0; --cropper-width: 1; --cropper-height: 1"> <img class="cropper-image" src="/demo/dawn.svg" alt="A pier at dawn" width="640" height="400"> <div class="cropper-box" role="application" aria-roledescription="crop box" tabindex="0" aria-label="Crop the picture"> <span class="cropper-handle cropper-handle-top cropper-handle-left"></span> <span class="cropper-handle cropper-handle-top"></span> <span class="cropper-handle cropper-handle-top cropper-handle-right"></span> <span class="cropper-handle cropper-handle-right"></span> <span class="cropper-handle cropper-handle-bottom cropper-handle-right"></span> <span class="cropper-handle cropper-handle-bottom"></span> <span class="cropper-handle cropper-handle-bottom cropper-handle-left"></span> <span class="cropper-handle cropper-handle-left"></span> </div> <p class="cropper-status" role="status"></p> </div> <div class="flex flex-wrap items-center gap-xs"> <button type="button" class="btn btn-sm" data-rotate="-90"> <svg class="icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"> <path d="M3.1626 8.6029A4.8333 4.8333 0 0 0 12.5278 9.5552A4.8333 4.8333 0 0 0 4.5522 4.5549L2.653 6.3845A0.5001 0.5001 0 0 1 2.4222 6.492A0.7044 0.7044 0 0 1 1.8413 5.9111A0.4998 0.4998 0 0 1 1.9862 5.6401L3.8478 3.8451Q4.7383 2.9615 5.9133 2.5222Q7.2234 2.0323 8.6132 2.1898Q10.003 2.3473 11.1703 3.1179A5.8276 5.8276 0 0 1 13.4737 9.8799Q13.0195 11.2028 12.0149 12.176A5.8276 5.8276 0 0 1 4.9149 12.9636Q3.7213 12.2343 2.9883 11.0431Q2.3309 9.9747 2.1708 8.7305A0.5 0.5 0 0 1 2.5032 8.1942Q2.6066 8.1862 2.7088 8.1685A0.4998 0.4998 0 0 1 3.1626 8.6029Z" fill="currentColor" stroke="none" fill-rule="evenodd" /> <path d="M2.3333 2.3333L2.3333 5.8A0.2 0.2 0 0 0 2.5333 6L6 6" /> </svg>Rotate left</button> <button type="button" class="btn btn-sm" data-rotate="90"> <svg class="icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"> <path d="M3.1626 8.6029A4.8333 4.8333 0 0 0 12.5278 9.5552A4.8333 4.8333 0 0 0 4.5522 4.5549L2.653 6.3845A0.5001 0.5001 0 0 1 2.4222 6.492A0.7044 0.7044 0 0 1 1.8413 5.9111A0.4998 0.4998 0 0 1 1.9862 5.6401L3.8478 3.8451Q4.7383 2.9615 5.9133 2.5222Q7.2234 2.0323 8.6132 2.1898Q10.003 2.3473 11.1703 3.1179A5.8276 5.8276 0 0 1 13.4737 9.8799Q13.0195 11.2028 12.0149 12.176A5.8276 5.8276 0 0 1 4.9149 12.9636Q3.7213 12.2343 2.9883 11.0431Q2.3309 9.9747 2.1708 8.7305A0.5 0.5 0 0 1 2.5032 8.1942Q2.6066 8.1862 2.7088 8.1685A0.4998 0.4998 0 0 1 3.1626 8.6029Z" fill="currentColor" stroke="none" fill-rule="evenodd" transform="translate(16 0) scale(-1 1)" /> <path d="M2.3333 2.3333L2.3333 5.8A0.2 0.2 0 0 0 2.5333 6L6 6" transform="translate(16 0) scale(-1 1)" /> </svg>Rotate right</button> </div> </div> <div class="flex flex-col gap-md min-w(0)"> <div class="well overflow-hidden flex items-center justify-center h(220)" data-stage aria-label="The adjusted picture" role="img"></div> <div class="segmented segmented-sm" role="radiogroup" aria-label="Show the picture"> <label class="segmented-item"> <input type="radio" class="segmented-input" name="adjust-mode" value="fit" checked>Fit</label> <label class="segmented-item"> <input type="radio" class="segmented-input" name="adjust-mode" value="fill">Fill</label> <label class="segmented-item"> <input type="radio" class="segmented-input" name="adjust-mode" value="tile">Tile</label> </div> <div class="grid gap-sm"> <div class="field"> <div class="flex items-baseline justify-between"> <label for="adjust-brightness">Brightness</label> <output class="fg-text-muted" for="adjust-brightness" data-for="brightness">100%</output> </div> <input type="range" class="slider" id="adjust-brightness" name="brightness" min="0" max="200" value="100"> </div> <div class="field"> <div class="flex items-baseline justify-between"> <label for="adjust-contrast">Contrast</label> <output class="fg-text-muted" for="adjust-contrast" data-for="contrast">100%</output> </div> <input type="range" class="slider" id="adjust-contrast" name="contrast" min="0" max="200" value="100"> </div> <div class="field"> <div class="flex items-baseline justify-between"> <label for="adjust-saturation">Saturation</label> <output class="fg-text-muted" for="adjust-saturation" data-for="saturation">100%</output> </div> <input type="range" class="slider" id="adjust-saturation" name="saturation" min="0" max="200" value="100"> </div> </div> <div class="flex flex-wrap gap-xs"> <button type="button" class="btn btn-sm" data-reset>Reset</button> </div> </div> </div> <details class="mt-lg"> <summary class="text-sm fg-text-strong">What the page hands on</summary> <pre class="code-block mt-sm"><code data-output></code></pre> </details></section>import { cropper } from '@master/ui/behaviors/cropper.js'/** * Adjust a picture without changing it: crop it with the cropper, turn it a quarter at a time, and set its * brightness, contrast and saturation. What the page hands on is the original file and the adjustments as data; * cutting and encoding the picture is the application's image pipeline. The preview shows the adjustments with * the CSS filters that are exactly them; nothing here pretends to be a colour grade. * * Returns the function that stops it, which releases the object URL of a chosen picture. */export function mount(root) { const controller = new AbortController() const { signal } = controller const $ = (selector) => root.querySelector(selector) const image = $('.cropper-image') const stage = $('[data-stage]') const input = $('input[type="file"]') const clear = $('[data-clear]') const error = $('[data-error]') const output = $('[data-output]') // The picture's own size, in the pixels the crop is measured in; its rendered size is something else. const size = () => ({ width: Number(image.getAttribute('width')), height: Number(image.getAttribute('height')) }) const initial = { src: image.getAttribute('src'), alt: image.getAttribute('alt') } /** The original file, or null for the sample picture, and the object URL it is shown by. */ let file = null let url = null const adjustments = { crop: null, rotate: 0, brightness: 100, contrast: 100, saturation: 100, mode: 'fit' } let crop = cropper($('.cropper')) adjustments.crop = crop.value /** The adjusted picture: the crop, turned and filtered, shown fit, fill or tiled in the stage. */ function paint() { const { crop: box, rotate, brightness, contrast, saturation, mode } = adjustments const turned = Math.abs(rotate) % 180 === 90 const width = turned ? box.height : box.width const height = turned ? box.width : box.height // The stage is a size container, so the result can be sized against it: contained to fit, covering to fill. stage.style.containerType = 'size' const ratio = width / height const tile = document.createElement('div') tile.style.cssText = [ `aspect-ratio: ${width} / ${height}`, `filter: brightness(${brightness}%) contrast(${contrast}%) saturate(${saturation}%)`, mode === 'fit' ? `width: min(100cqw, 100cqh * ${ratio})` : mode === 'fill' ? `width: max(100cqw, 100cqh * ${ratio})` : 'width: 100cqw; height: 100cqh; aspect-ratio: auto', 'flex: none; position: relative; overflow: hidden', ].join(';') // The crop's picture, turned about its middle: a background sized so the crop fills the box before it turns. const picture = document.createElement('div') const { width: pictureWidth, height: pictureHeight } = size() const scaleX = pictureWidth / box.width * 100 const scaleY = pictureHeight / box.height * 100 picture.style.cssText = [ 'position: absolute; left: 50%; top: 50%', `width: ${turned ? (height / width) * 100 : 100}%`, `height: ${turned ? (width / height) * 100 : 100}%`, `translate: -50% -50%; rotate: ${rotate}deg`, `background-image: url("${image.currentSrc || image.src}")`, mode === 'tile' ? `background-size: ${scaleX / 4}% ${scaleY / 4}%; background-repeat: repeat` : `background-size: ${scaleX}% ${scaleY}%; background-repeat: no-repeat`, `background-position: ${box.width >= pictureWidth ? 0 : box.x / (pictureWidth - box.width) * 100}% ${box.height >= pictureHeight ? 0 : box.y / (pictureHeight - box.height) * 100}%`, ].join(';') tile.replaceChildren(picture) stage.replaceChildren(tile) stage.setAttribute('aria-label', `${image.alt}, adjusted`) for (const name of ['brightness', 'contrast', 'saturation']) $(`output[data-for="${name}"]`).textContent = `${adjustments[name]}%` output.textContent = JSON.stringify({ file: file ? { name: file.name, type: file.type, size: file.size } : { sample: initial.src }, ...adjustments, }, null, 2) } /** Counts the pictures asked for, so one that finishes loading late does not replace a later choice. */ let latest = 0 /** Show another picture: the cropper starts over on it, and the old object URL is released. */ async function show(src, alt, chosen) { const turn = ++latest const probe = new Image() probe.src = src // An alert that is already shown says nothing when it is shown again: it leaves first, so each failure is heard. error.hidden = true try { await probe.decode() } catch { if (chosen) URL.revokeObjectURL(src) if (turn !== latest) return error.hidden = false input.value = '' return } // A picture chosen since this one began to load is the one to show: this one is let go. if (turn !== latest) { if (chosen) URL.revokeObjectURL(src) return } if (url && url !== src) URL.revokeObjectURL(url) url = chosen ? src : null file = chosen image.src = src image.alt = alt image.setAttribute('width', String(probe.naturalWidth)) image.setAttribute('height', String(probe.naturalHeight)) crop() crop = cropper($('.cropper')) adjustments.crop = crop.value adjustments.rotate = 0 clear.disabled = !chosen paint() } input.addEventListener('change', () => { const chosen = input.files?.[0] if (chosen) show(URL.createObjectURL(chosen), chosen.name, chosen) }, { signal }) clear.addEventListener('click', () => { input.value = '' show(initial.src, initial.alt, null) input.focus() }, { signal }) $('.cropper').addEventListener('change', () => { adjustments.crop = crop.value paint() }, { signal }) $('.cropper').addEventListener('input', () => { adjustments.crop = crop.value paint() }, { signal }) root.addEventListener('click', (event) => { const turn = event.target.closest('[data-rotate]') if (turn) { adjustments.rotate = (adjustments.rotate + Number(turn.dataset.rotate) + 360) % 360 paint() } else if (event.target.closest('[data-reset]')) { Object.assign(adjustments, { rotate: 0, brightness: 100, contrast: 100, saturation: 100 }) for (const name of ['brightness', 'contrast', 'saturation']) $(`input[name="${name}"]`).value = '100' crop.value = { x: 0, y: 0, ...size() } adjustments.crop = crop.value paint() } }, { signal }) root.addEventListener('input', (event) => { const range = event.target.closest('input[type="range"][name]') if (range) { adjustments[range.name] = Number(range.value) paint() } const mode = event.target.closest('input[name="adjust-mode"]') if (mode?.checked) { adjustments.mode = mode.value paint() } }, { signal }) paint() return () => { controller.abort() // A picture still loading is not shown on an example that has been taken away. latest += 1 crop() if (url) URL.revokeObjectURL(url) }}#역할 분담
| 부분 | 담당 |
|---|---|
| 자르기 도구와 그 동작 | 자르기 상자의 가장자리, 키보드, 포인터, 사진 자체의 픽셀 단위로 표시한 자르기 영역 |
| 네이티브 입력 요소 | 파일 선택, 밝기·대비·채도 범위 입력, 표시 방식 라디오 버튼 |
| 페이지 | 파일 읽기, 파일을 표시하는 객체 URL, 조정 내용 미리보기, 전달할 데이터 |
| 애플리케이션 | 저장할 사진의 자르기, 회전, 필터 적용, 인코딩, 업로드 |
페이지는 자체 미리보기에 filter와 transform을 설정합니다. 사진을 그리는 Master UI 동작은 없습니다. 이 예제에서 데이터가 스타일을 결정하는 곳은 이곳뿐이며, 이 처리는 페이지에 남겨 둡니다.
#파일
- 선택. 버튼의 레이블 안에 있는 파일 입력에
accept="image/*"를 지정합니다. 사진은 표시하기 전에HTMLImageElement.decode()로 디코딩하므로, 사진이 아닌 파일은 알림의 메시지와 함께 거부되고 현재 표시 중인 사진은 그대로 유지됩니다. - 표시. 선택한 파일은 객체 URL로 표시합니다. 사진을 바꾸거나 지우면
URL.revokeObjectURL()로 이전 URL을 해제하며, 예제가 중지될 때mount()가 반환하는 함수도 같은 작업을 합니다. - 다시 시작. 자르기 도구는
cropper-image의width와height에서 사진 크기를 읽으므로, 새 사진은 원본 크기로 두 값을 설정하고 자르기 도구를 사진 전체에 다시 연결합니다. - 개인 정보. 파일은 브라우저 밖으로 나가지 않습니다. 버튼 옆에 이 사실을 알려 주세요.
#조정 내용
- 자르기. 자르기 도구의
value이며, 사진의 픽셀 단위로 표시한{ x, y, width, height }입니다. 상자에서 발생하는input과change마다 읽습니다. - 회전. 왼쪽이나 오른쪽으로 90도씩 회전하며, 0, 90, 180, 270도로 표시합니다. 자르기 영역은 사진 자체의 방향을 기준으로 유지되고, 미리보기에서는 자른 사진을 중심점을 기준으로 회전하므로 90도와 270도에서는 너비와 높이가 서로 바뀝니다.
- 밝기·대비·채도. 각 값은 0%부터 200%까지 설정할 수 있고, 100%는 원본 그대로입니다. CSS에는 정확히 이 세 가지가
brightness(),contrast(),saturate()로 있으므로, 미리보기는 같은 세 가지를 적용하는 이미지 파이프라인의 결과와 같습니다. - 표시 방식. 맞춤은 결과 전체를 미리보기 영역 안에 표시하고, 채우기는 결과로 영역 전체를 덮으며, 바둑판식은 사진을 배경으로 사용할 때처럼 결과를 반복합니다.
초기화하면 밝기·대비·채도와 자르기 영역이 원래대로 돌아가고 사진은 유지됩니다.
{ "file": { "name": "dawn.jpg", "type": "image/jpeg", "size": 482113 }, "crop": { "x": 160, "y": 80, "width": 1280, "height": 800 }, "rotate": 90, "brightness": 110, "contrast": 100, "saturation": 85, "mode": "fit"}원본 File과 이 객체를 함께 애플리케이션에 전달하세요. 애플리케이션은 원본 해상도의 사진을 같은 방식으로 자르고, 회전하고, 필터를 적용할 수 있으며, 원본을 보관해 나중에 다시 조정할 수 있습니다.
#이 예제에서 다루지 않는 것
완전한 사진 편집기에는 밝기·대비·채도 외에도 색온도, 하이라이트와 그림자, 곡선, 내보낸 파일 등이 있습니다. CSS에는 이에 해당하는 필터가 없고, 근사치로 흉내 내면 저장된 사진에는 없는 결과를 독자에게 보여 주게 되므로 이 예제에서는 흉내 내지 않고 제외합니다. 캔버스나 OffscreenCanvas로 브라우저에서 결과를 인코딩할지는 애플리케이션이 결정할 일이며, 여기서는 다루지 않습니다.
#접근성
- 파일 입력은 레이블이 있는 버튼 안의 실제 입력 요소이며 Tab으로 이동할 수 있습니다. 그 아래의 도움말은 사진이 어디로 전달되는지 알려 줍니다.
- 자르기 상자는 자르기 도구의 키보드 조작을 지원하며, 자르기 영역이 바뀔 때마다 상태 영역이 새 자르기 영역을 알려 줍니다.
- 밝기, 대비, 채도는 각각 레이블이 있는 범위 입력으로 제공되며, 각 입력 옆에 값이 표시됩니다. 회전 버튼의 이름은 회전 방향입니다.
- 미리보기 이름은 “새벽의 부두, 조정됨”처럼 사진 자체의 설명에 “조정됨”을 붙여 지정합니다. 사진에 적용한 내용은 그림뿐만 아니라 페이지가 표시하는 데이터에도 들어 있습니다.