wjiushiwya
wjiushiwya

Reputation: 69

How to load black white image into metal texture

I use two methods to load black white image texture in metal as below:

 //1.
    mtltexture01 = [textureLoader newTextureWithName:@"texture02"
                                         scaleFactor:1.0
                                              bundle:nil
                                             options:textureLoaderOptions
                                               error:&error];



 //2.
    UIImage *img = [UIImage imageNamed:@"texture02"];

    mtltexture01 = [textureLoader newTextureWithCGImage:img.CGImage options:textureLoaderOptions error:&error];

but both crash, the error log is

"Error Domain=MTKTextureLoaderErrorDomain Code=0 "Image decoding failed" UserInfo={NSLocalizedDescription=Image decoding failed, MTKTextureLoaderErrorKey=Image decoding failed}",

how to fix this issue? Also if I load the colorful image into metal, it runs.enter image description here

Upvotes: 1

Views: 991

Answers (2)

Openningapps
Openningapps

Reputation: 111

I have had this problem in the past, and I just hit it again. I am quite confident that this is a bug in IOS. If your RGB image only has greyscale colors and transparency, it gives the error that you show.

The fix is to change just one pixel of the image to not be greyscale. So find a black pixel and change its color to #000001 or change a white pixel to #fffffe. Then everything works as it should -- without any changes to your swift code.

Upvotes: 0

Ol Sen
Ol Sen

Reputation: 3368

-(id<MTLTexture>)textureWithName:(NSString*)imgname UsingDevice:(id<MTLDevice>)device {

     MTKTextureLoader* textureLoader = [[MTKTextureLoader alloc] initWithDevice:device];

     NSDictionary *textureLoaderOptions = @{
         MTKTextureLoaderOptionTextureUsage : @(MTLTextureUsageShaderRead),
         MTKTextureLoaderOptionTextureStorageMode : @(MTLStorageModePrivate)
     };

     return [textureLoader newTextureWithName:imgname
         scaleFactor:1.0
         bundle:nil
         options:textureLoaderOptions
         error:nil];
}

and in your metal configurations

id<MTLTexture> mtltexture01;

mtltexture01 = [self textureWithName:@"texture02" UsingDevice:device];

Keep in mind texture02 is a filename and the file needs to be available in your apps assets. You can store the image as MTLTexture into your asset in Xcode and so the conversion is done at build time.

Also check if the image contains at least proper opacity and is one of PNG, JPEG, or TIFF format. There is known loader trouble when textures contain only gray/ black colors and 0% transparency is used.

later integrate your texture to the renderEncoder/commandEncoder

screenshot: Xcode Assets Texture Configurator enter image description here

Upvotes: 0

Related Questions