为了账号安全,请及时绑定邮箱和手机立即绑定

如何从字节数组创建图像并显示它?

如何从字节数组创建图像并显示它?

C#
白衣非少年 2022-07-23 16:21:21
我想从图像文件中获取数据并在 Unity 可以读取的纹理中显示该信息。我能够将像素信息放入字节数组中,但屏幕上没有任何显示。我如何真正让图像显示?     pcxFile = File.ReadAllBytes("Assets/5_ImageParser/bagit_icon.pcx");     int startPoint = 128;     int height = 152;      int width = 152;      target = new Texture2D(height, width);     for (var y = 0; y < height; y++)     {         for (var x = 0; x < width; x++)         {             timesDone ++;             pixels[x, y] = new Color(pcxFile[startPoint], pcxFile[startPoint+1], pcxFile[startPoint+2]);             startPoint += 4;             target.SetPixel(x, y, pixels[x, y]);         }                 }     target.Apply();     target.EncodeToJPG();
查看完整描述

1 回答

?
HUH函数

TA贡献1836条经验 获得超4个赞

好吧,(假设您正确获取像素数据)您必须将创建的纹理分配给某些东西......


我会使用例如RawImage,因为它不需要 a Sprite(就像UI.Image组件一样 - 另请参阅RawImage Manual):


// Reference this in the Inspector

public RawImage image;


//...


pcxFile = File.ReadAllBytes("Assets/5_ImageParser/bagit_icon.pcx");

int startPoint = 128;

int height = 152; 

int width = 152; 

target = new Texture2D(height, width);

for (var y = 0; y < height; y++)

{

    for (var x = 0; x < width; x++)

    {

        timesDone ++;

        pixels[x, y] = new Color(pcxFile[startPoint], pcxFile[startPoint+1], pcxFile[startPoint+2]);

        startPoint += 4;

        target.SetPixel(x, y, pixels[x, y]);

    }            

}

target.Apply();

// You don't need this. Only if you are also going to save it locally

// as an actual *.jpg file or if you are going to

// e.g. upload it later via http POST

//

// In this case however you would have to asign the result 

// to a variable in order to use it later

//var rawJpgBytes = target.EncodeToJPG();


// Assign the texture to the RawImage component

image.texture = target;

或者,与普通Image组件一起使用Sprite从您的纹理创建一个Sprite.Create:


// Reference this in the Inspector

public Image image;


// ...


var sprite = Sprite.Create(target, new Rect(0.0f, 0.0f, target.width, target.height), new Vector2(0.5f, 0.5f), 100.0f);


image.sprite = sprite;

提示 1

为了获得正确的纵横比,我通常使用一个小技巧:


为这个 RawImage 创建一个父对象

RectTransform在父级中设置所需的“最大尺寸”

RawImage在/旁边Image(在子对象上)添加一个AspectRatioFitter(另见AspectRatioFitter Manual)并设置AspectMode为FitInParent.

现在在代码中调整纵横比(从纹理中获取):


public RawImage image;

public AspectRatioFitter fitter;


//...


image.texture = target;


var ratio = target.width / target.height;

fitter.aspectRatio = ratio;

提示 2对所有像素调用一次比重复

调用“便宜” :SetPixelsSetPixel


// ...


startPoint = 0;

pixels = new Color[width * height]();

for(int i = 0; i < pixels.Length; i++)

{

    pixels[i] = new Color(pcxFile[startPoint], pcxFile[startPoint+1], pcxFile[startPoint+2]);

    startPoint += 4;

}


target.SetPixels(pixels);

target.Apply();


// ...

(我不知道您的pcx格式究竟是如何工作的,但也许您甚至可以使用LoadRawTextureData


查看完整回答
反对 回复 2022-07-23
  • 1 回答
  • 0 关注
  • 143 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号