【发布时间】:2021-10-12 06:21:37
【问题描述】:
我现在有一张图片,我想将那张图片分成三部分。
如何在 React-native 中做到这一点?我尝试了不同的包,但没有得到我的应用程序中确切需要的适当结果。
我附上了我的要求所需的图像和输出。 分割图像后,我需要三个不同的图像。
【问题讨论】:
-
你找到解决办法了吗?
标签: reactjs react-native react-native-image
我现在有一张图片,我想将那张图片分成三部分。
如何在 React-native 中做到这一点?我尝试了不同的包,但没有得到我的应用程序中确切需要的适当结果。
我附上了我的要求所需的图像和输出。 分割图像后,我需要三个不同的图像。
【问题讨论】:
标签: reactjs react-native react-native-image
您可以将图像加载到画布中,然后使用 vanilla js 将其拆分。对于画布,您可以搜索 react-native 的库。 这是一个使用js分割图像的示例代码。
JS:
var c = document.getElementById("canvas"),
w = innerWidth,
h = innerHeight;
c.width = w;
c.height = h;
var ctx = c.getContext("2d"),
input = document.getElementById("input"),
reader = new FileReader(),
img = new Image(),
imgW, //px
imgH, //px
imgData,
tileDim = 50, //tile dimensions px
tileCountX, //how many tiles we can fit
tileCountY;
//read file input
input.onchange = function() {
reader.readAsDataURL(input.files[0]);
reader.onload = function() {
img.src = reader.result;
img.onload = function() {
//start
init();
var tiles = getTiles();
drawTiles(tiles);
}
}
}
function init() {
imgW = img.width;
imgH = img.height;
//check how many full tiles we can fit
//right and bottom sides of the image will get cropped
tileCountX = ~~(imgW / tileDim);
tileCountY = ~~(imgH / tileDim);
ctx.drawImage(img, 0, 0);
imgData = ctx.getImageData(0, 0, imgW, imgH).data;
ctx.clearRect(0, 0, w, h);
}
//get imgdata index from img px positions
function indexX(x) {
var i = x * 4;
if (i > imgData.length) console.warn("X out of bounds");
return i;
}
function indexY(y) {
var i = imgW * 4 * y;
if (i > imgData.length) console.warn("Y out of bounds");
return i;
}
function getIndex(x, y) {
var i = indexX(x) + indexY(y);
if (i > imgData.length) console.warn("XY out of bounds");
return i;
}
//get a tile of size tileDim*tileDim from position xy
function getTile(x, y) {
var tile = [];
//loop over rows
for (var i = 0; i < tileDim; i++) {
//slice original image from x to x + tileDim, concat
tile.push(...imgData.slice(getIndex(x, y + i), getIndex(x + tileDim, y + i)));
}
//convert back to typed array and to imgdata object
tile = new ImageData(new Uint8ClampedArray(tile), tileDim, tileDim);
//save original position
tile.x = x;
tile.y = y;
return tile;
}
//generate all tiles
function getTiles() {
var tiles = [];
for (var yi = 0; yi < tileCountY; yi++) {
for (var xi = 0; xi < tileCountX; xi++) {
tiles.push(getTile(xi * tileDim, yi * tileDim));
}
}
return tiles;
}
//and draw with offset
var offset = 1.1;
function drawTiles(tiles) {
tiles.forEach((d,i) => ctx.putImageData(d, d.x * offset, d.y * offset));
//more interesting effects are easy to do:
//tiles.forEach((d,i) => ctx.putImageData(d, d.x * i * 0.01, d.y * i * 0.01));
//for efficiency in animation etc tiles should be converted to image object
}
CSS:
body{
margin:0;
}
canvas{
display:block;
width:100%;
height:100%;
}
input{
position:absolute;
top:0;
}
HTML(哈巴狗):
input#input(type="file")
canvas#canvas
通过谷歌搜索找到了代码。 Link
【讨论】: