ImageConversion.EncodeArrayToJPG

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

ImageConversion.EncodeArrayToJPG

Объявление

public static byte[] EncodeArrayToJPG(Array array, Experimental.Rendering.GraphicsFormat format, uint width, uint height, uint rowBytes, int quality);

Параметры

array Массив байтов для преобразования.
format Пиксельный формат данных изображения.
width Ширина данных изображения в пикселях.
height Высота данных изображения в пикселях.
rowBytes Длина одной строки в байтах.
quality Качество JPG для кодирования, 1..100 (по умолчанию 75).

Описание

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

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

Закодированные данные JPG не будут иметь альфа-канала, а для одноканальных красных текстур ( R8, R16, RFloat и RHalf ) закодированные данные JPG будут в 8-битных оттенках серого.

Этот метод является потокобезопасным.

Если передать rowBytes значение 0, длина строки в байтах будет автоматически рассчитана.

// Saves screenshot as JPG file.
using System.Collections;
using System.IO;
using UnityEngine;

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 bytes in JPG format
        byte[] bytes = ImageConversion.EncodeArrayToJPG(tex.GetRawTextureData(), tex.graphicsFormat, (uint)width, (uint)height);
        Object.Destroy(tex);

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

Смотрите так же: EncodeToJPG, EncodeNativeArrayToJPG, EncodeArrayToPNG, EncodeArrayToTGA, EncodeArrayToEXR.

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