'Convert string that is basically a nested array of integers to an array and display an image [closed]
I have an array coming from a get request that is returned to me as a string, in this form: [[[red [row data],[row data]],[blue [row data],[row data]]…]. It is essentially an image with 3-tuples of 0-255 values representing RGB values, and I am trying to display it in my React app as an image. Heres also a snippet of the array: "[[[68, 81, 237], [67, 80, 236], [64, 79, 235], [61, 79, 234], [62, 80, 235], [61, 81, 236], [61, 83, 238], [62, 84, 239], [62, 84, 239], [62, 84, 239],"
What is the easiest way to convert this into some type of image I can display on a web page?
Solution 1:[1]
You can render divs as to be pixels and draw it as below by using Array.map twice to iterate over the rows and columns. Use a 2D array to store the color information. You can adjust the pixel size by changing the width and height styles.
const data = [
[
[6, 81, 237],
[67, 0, 236],
[64, 79, 23]
],
[
[61, 79, 234],
[20, 220, 15],
[6, 33, 106]
],
[
[255, 83, 238],
[62, 84, 239],
[62, 228, 229]
]
];
function App() {
return (
<div className="App">
{data.map((row) => (
<div style={{ display: "flex" }}>
{row.map(([red, green, blue]) => (
<div
style={{
backgroundColor: `rgb(${red},${green},${blue})`,
width: "30px",
height: "30px"
}}
></div>
))}
</div>
))}
</div>
);
}
ReactDOM.render(<App/>, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
