Uiimageview Not Showing Transparency of Png Images from Uiimagepickercontroller

UIImageView not showing transparency of PNG Images from UIImagePickerController

Yes, the call to UIImageJPEGRepresentation will convert the resulting image into a JPEG, which doesn't support transparency.

BTW, if your intent is to get the NSData for the image for other reasons (e.g. uploading to server, emailing, etc.), I would recommend against both UIImageJPEGRepresentation and UIImagePNGRepresentation. They lose meta data, can make the asset larger, if suffer some image degradation if you use quality factor of less than 1, etc.

Instead, I'd recommend going back and get the original asset from the Photos framework. Thus, in Swift 3:

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let url = info[UIImagePickerControllerReferenceURL] as? URL {
let result = PHAsset.fetchAssets(withALAssetURLs: [url], options: nil)
if let asset = result.firstObject {
let manager = PHImageManager.default()
manager.requestImageData(for: asset, options: nil) { imageData, dataUTI, orientation, info in
if let fileURL = info!["PHImageFileURLKey"] as? URL {
let filename = fileURL.lastPathComponent
// use filename here
}

// use imageData here
}
}
}

picker.dismiss(animated: true)
}

If you have to support iOS 7, too, you'd use the equivalent ALAssetsLibrary API, but the idea is the same: Get the original asset rather than round-tripping it through a UIImage.

(For Swift 2 rendition, see previous revision of this answer.)

IOS Objective C load a PNG file with transparent background to a UIImageView

Your primary issue is the use of the UIImagePickerControllerEditedImage instead of UIImagePickerControllerOriginalImage when getting the selected image. The edited image loses the alpha channel resulting in black instead of transparency.

You also have no need for the imageWithImage: method.

How to Save UIImage to a Transparent PNG?

Solved the problem!

The block of codes that I posted with my question have nothing wrong. The problem was occurring from iTunes, when I synchronize images from my Mac to my iPhone iTunes convert them to JPEG and because of this images loses their transparency etc... and when I select images using my app, I was selecting them as JPEG without being aware and that's why I had these problems.

So I came up with a solution to have images via email. I just send them from my mac to iPhone with e-mail, and by this images didn't lose anything as a feature. After that when I used them in app as a right image, the program worked as it supposed to be.

Loading a png into a UIImageView iOS

This is the kind of task that is easier to do from code than from Interface "Crappy" Builder:

CGRect imageFrame = CGRectMake(x, y, width, height);

UIImage *image1 = // however you obtain your 1st image
UIImage *image2 = // however you obtain your 2nd image

UIImageView *imgView1 = [[UIImageView alloc] initWithImage:image1];
// Adjust the alpha of the view
imgView1.alpha = 1.0f; // This is most advisably 1.0 (always)
imgView1.backgroundColor = [UIColor clearColor];
imgView1.frame = imageFrame;

UIImageView *imgView2 = [[UIImageView alloc] initWithImage:image2];
// Adjust the alpha of the view
imgView1.alpha = 0.5f; // or whatever you find practical
imgView1.backgroundColor = [UIColor clearColor];
imgView2.frame = imageFrame;

// Assume a view controller
[self.view addSubview:imgView1];
[self.view addSUbview:imgView2]; // add the image view later which you wanna be on the top of the other one

// If non-ARC environment, we need to take care of the percious RAM
[imgView1 release];
[imgView2 release];

Incorrect saving of transparent UIImage to Photo Library as png with UIImageWriteToSavedPhotosAlbum

The problem is that UIImageWriteToSavedPhotosAlbum does not handle properly saving a UIImage with premultiplied alpha (or at least the result of saving such image is not what you expect) and your cropping method uses premultipliedLast format. You also can't just simply change CGImageAlphaInfo to a non-premultiplied format because it is not supported there (you will see an error CGBitmapContextCreate: unsupported parameter combination if you try that). But what you can do is convert the cropped image to CIImage, unpremultiply alpha and convert back to UIImage. To do that your saving code could look like below (however I recommend removing force unwrapping from this code if you plan to use it in final app):

let image = maskedImage?.cropAlpha()

let ciImage = CIImage(image: image!)!.unpremultiplyingAlpha()
let uiImage = UIImage(ciImage: ciImage)

let imagePNGData = uiImage.pngData()
let imagePNG = UIImage(data: imagePNGData!)

UIImageWriteToSavedPhotosAlbum(imagePNG!, nil, nil, nil)

I have a png file with no background, how can I create a clear color background for this image in iOS?

It seems a bit of excess work to use UIGraphicsGetImageFromCurrentImageContext to generate an image from context, when you can just create an image from a file.

As first mentioned it is required to have Opaque = NO:

UIGraphicsBeginImageContextWithOptions(size, NO, 0.0);

My bet is its the image itself, because the whole thing is faded.

Make 100% certain that the passed colour is a clear colour for:

backgroundView.backgroundColor = color

You could create a bitmap context and use that instead:

CGContextRef context = CGBitmapContextCreate(NULL,
width,
height,
8,
0,
rgbColorSpace,
kCGImageAlphaPremultipliedLast);

Rather than using the current context and you can use:

myGeneratedImage  = CGBitmapContextCreateImage(context)

Drawing is easy as pie:

CGContextDrawImage(realContext,bounds,myGeneratedImage)

CGImage from images stored on iCloud look wrong

The reason why the image looked blurry and without alpha seems to be that Photos streams Jpeg-compressed images from iCloud by default. Even if your original image would be smaller without compression, like in this pixel art example.

As pointed out by Rob, a way to verify that this is the case is to change your Photos settings. From the Settings app:

Settings -> Photos -> Download and Keep Originals

This would fix the issue, but of course it's not desirable. If you want to keep using Photos, instead of implementing your own iCloud solution, while keeping the Optimize iPhone Storage setting, you can use PhotoKit to retrieve the original image.

Replace this code,

    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
if let image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage {
loadImageInMemory(image)
}
picker.dismiss(animated: true, completion: nil)
self.presentingViewController?.dismiss(animated: true, completion: nil)
}

by this other code:

import Photos

// ...

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
// it will be loaded asynchronously
loadImageFromPicker(info: info)
picker.dismiss(animated: true, completion: nil)
self.presentingViewController?.dismiss(animated: true, completion: nil)
}

private func loadImageFromPicker(info: [UIImagePickerController.InfoKey : Any]) {
var phAsset: PHAsset?
if #available(iOS 11.0, *) {
phAsset = info[UIImagePickerController.InfoKey.phAsset] as? PHAsset
} else {
// Fallback on earlier versions
if let referenceURL = info[UIImagePickerController.InfoKey.referenceURL] as? URL {
let fetchResult = PHAsset.fetchAssets(withALAssetURLs: [referenceURL], options: nil)
phAsset = fetchResult.firstObject
}
}
guard let asset = phAsset else {
return
}
// size doesn't matter, because resizeMode = .none
let size = CGSize(width: 32, height: 32)
let options = PHImageRequestOptions()
options.version = .original
options.deliveryMode = .highQualityFormat
options.resizeMode = .none
options.isNetworkAccessAllowed = true
PHImageManager.default().requestImage(for: asset, targetSize: size, contentMode: .aspectFit, options: options) { [weak self] (image, info) in
if let s = self, let image = image {
s.loadImageInMemory(image)
}
}
}

This code will work with both local images and iCloud images.



Related Topics



Leave a reply



Submit