I am making a photo maker type of app, where it arranges images in a grid and then you can export the image.
Here’s what I do using one of the algorithms:
The part to be exported is ‘Paper’ (say).
I take the whole screenshot as a Texture2D of the game window with some Unity function I do remember, and then I Texture2D.GetPixels() from the bottom right of the ‘Paper’, width and height equal to the ‘Paper’ height and width in screen units.
Yeah, I also used __RenderTexture__s, yeah, it also works, yeah, it’s in the app too, but hear me out.
Then I just create another Texture2D and use SetPixels() to copy the image, and then, just export it.
I am really frustrated. You can say that because I am gonna post the whole code from my editor:
Vector2 res_size;
if (Safe_toggle.isOn)
{
res_size = new Vector2(Screen.width * (scaler.res_mul + 1), Screen.height * (scaler.res_mul + 1));
}
else
{
res_size = new Vector2(Screen.width * scaler.res_mul, Screen.height * scaler.res_mul);
}
if (res_size.x > SystemInfo.maxTextureSize || res_size.y > SystemInfo.maxTextureSize || res_size.x > 16384 || res_size.y > 16384)
{
Error.SetActive(true);
Main_gr.alpha = 1;
return return_new();
}
Texture2D screenshot = ScreenCapture.CaptureScreenshotAsTexture(scaler.res_mul);
Debug.Log($"{screenshot.width} S {screenshot.height}");
int multiplier = scaler.res_mul;
Vector2 bottom_leftt = main_camera.ViewportToWorldPoint(new Vector2(0, 0));
Vector2 Canvas_size = main_camera.WorldToScreenPoint(bottom_leftt + (Vector2)Canvas_collider.bounds.size);
Debug.Log($"CANVAS {Canvas_collider.bounds.size} SCREEN {Canvas_size}");
Vector2 bottom_leftt_canvas = Canvas_collider.transform.position - Canvas_collider.bounds.extents;
Vector2 bottom_left_canvas = main_camera.WorldToScreenPoint(bottom_leftt_canvas);
int srcX = Mathf.CeilToInt((bottom_left_canvas.x) * multiplier);
int srcY = Mathf.CeilToInt(bottom_left_canvas.y * multiplier);
int srcWidth = Mathf.CeilToInt(Canvas_size.x * multiplier);
int srcHeight = Mathf.CeilToInt(Canvas_size.y * multiplier);
Color[] req_colors = screenshot.GetPixels(srcX, srcY, srcWidth, srcHeight);
Texture2D Image = new Texture2D(srcWidth, srcHeight);
Image.SetPixels(req_colors);
Image.Apply();
var Bytes = Image.EncodeToPNG();
Destroy(screenshot);
Destroy(Image);
Image = null;
req_colors = null;
screenshot = null;
return Bytes;
So, the problem is, whenever I export the file, it keeps taking up huge amounts of memory (according to the resolution multiplier), but it never releases the memory. And after few times of exporting, the thing couldn’t allocate any more memory and just crashes.
I commented out the GetPixels(), the thing now doesn’t take more memory (obviously). It can also be SetPixels(), but I don’t know.
Also, it’s not ‘try something else then’, it’s more like, ‘why is it not working’ for me.
I will really appreciate if anyone can help me. Thank you!
PS - The app currently is focused around WebGL, but still…
