Search Unity

  1. Unity 2020.1 has been released.
    Dismiss Notice
  2. We are looking for feedback on the experimental Unity Safe Mode which is aiming to help you resolve compilation errors faster during project startup.
    Dismiss Notice
  3. Good news ✨ We have more Unite Now videos available for you to watch on-demand! Come check them out and ask our experts any questions!
    Dismiss Notice

Taking screenshot of partial area

Discussion in 'Scripting' started by baylor, Jul 13, 2010.

  1. baylor

    baylor

    Joined:
    Oct 29, 2009
    Posts:
    25
    My game lets you dress up your character. i'd like to save off that image (but not the rest of the 800x600 screen) to a file. According to the help, i can use Application.CaptureScreen() to capture the full screen but how does one capture just one part of it?

    (Sorry if this is a common question. i searched first for "screenshot" but that produced tons of hits that weren't relevant (it's a popular key word))
     
    ina likes this.
  2. CaptainKiyaku

    CaptainKiyaku

    Joined:
    Feb 8, 2009
    Posts:
    324
    Code (csharp):
    1.  var width = 400;
    2.  var height = 300;
    3.  var startX = 200;
    4.  var startY = 100;
    5.  var tex = new Texture2D (width, height, TextureFormat.RGB24, false);
    6.  
    7.  tex.ReadPixels (Rect(startX, startY, width, height), 0, 0);
    8.  tex.Apply ();
    9.  
    10.  // Encode texture into PNG
    11.  var bytes = tex.EncodeToPNG();
    12.  Destroy(tex);
    13.  
    14.  File.WriteAllBytes(Application.dataPath + "/../SavedScreen.png", bytes);
    15.  
     
  3. JtheSpaceC

    JtheSpaceC

    Joined:
    Oct 5, 2014
    Posts:
    14
    Wow. 7 years later and no accepted answer.

    Well CaptainKiyaku's answer (with a little modification, below) still works.

    Code (CSharp):
    1. var width = 400;
    2.         var height = 300;
    3.         var startX = 200;
    4.         var startY = 100;
    5.         var tex = new Texture2D(width, height, TextureFormat.RGB24, false);
    6.  
    7.         Rect rex = new Rect(startX, startY, width, height);
    8.  
    9.         tex.ReadPixels(rex, 0, 0);
    10.         tex.Apply();
    11.  
    12.         // Encode texture into PNG
    13.         var bytes = tex.EncodeToPNG();
    14.         Destroy(tex);
    15.  
    16.         System.IO.File.WriteAllBytes(Application.dataPath + "SavedScreen.png", bytes);
     
    justahobbyisthere and ina like this.
  4. FenixShadow

    FenixShadow

    Joined:
    Dec 10, 2014
    Posts:
    2
    To make sure the screen is captured correctly, you should wait to perform ReadPixels until after the frame is fully rendered. You can accomplish this by calling your script (or at least ReadPixels and everything after) in the OnPostRender message or by using WaitForEndOfFrame.
     
    kk88 likes this.
unityunity