ImageConversion.EncodeToJPG

Unity · Версия 2020.3 LTS · Scripting · ImageConversion

ImageConversion.EncodeToJPG

Объявление

public static byte[] EncodeToJPG(Texture2D tex, int quality);

public static byte[] EncodeToJPG(Texture2D tex);

Параметры

tex Текстовая текстура для преобразования.
quality Качество JPG для кодирования, 1..100 (по умолчанию 75).

Описание

Кодирует эту текстуру в формат JPG.

Возвращенный массив байтов является "файлом" JPG. Вы можете записать их на диск, чтобы получить файл JPG, отправлять их по сети и т. д.

Эта функция работает только с несжатыми форматами текстур без HDR.

Texture.isReadable должно быть true. Закодированные данные JPG не будут иметь альфа-канала, а для одноканальных красных текстур ( R8, R16, RFloat и RHalf ), закодированные данные JPG будут в 8-битных оттенках серого.
// Saves screenshot as JPG file.
using UnityEngine;
using System.Collections;
using System.IO;

public class JPGScreenSaver : MonoBehaviour
{
    // Take a shot immediately
    IEnumerator Start()
    {
        yield return SaveScreenJPG();
    }

    IEnumerator SaveScreenJPG()
    {
        // Read the screen buffer after rendering is complete
        yield return new WaitForEndOfFrame();

        // Create a texture in RGB24 format the size of the screen
        int width = Screen.width;
        int height = Screen.height;
        Texture2D tex = new Texture2D(width, height, TextureFormat.RGB24, false);

        // Read the screen contents into the texture
        tex.ReadPixels(new Rect(0, 0, width, height), 0, 0);
        tex.Apply();

        // Encode the texture in JPG format
        byte[] bytes = tex.EncodeToJPG();
        Object.Destroy(tex);

        // Write the returned byte array to a file in the project folder
        File.WriteAllBytes(Application.dataPath + "/../SavedScreen.jpg", bytes);
    }
}

Смотрите так же: EncodeArrayToJPG, EncodeNativeArrayToJPG, EncodeToPNG, EncodeToTGA, EncodeToEXR.

Обновлено 17 ноября 2026 г.