rotate bitmap based on exif orientation

778 views
Skip to first unread message

Bruno

unread,
May 13, 2020, 11:58:37 PM5/13/20
to skia-discuss
What's the best way to rotate a bitmap based on exif data?

This is the code that I came up with, but it's slow and I think there's a better way to do it... I need to basically load a bitmap and return it rotated.

any tips on how to make it better?

thanks!

static bool LoadImage(const std::string& file, SkBitmap* bitmap)
{
sk_sp<SkData> data = SkData::MakeFromFileName(file.c_str());
if (!data) return false;

std::unique_ptr<SkCodec> codec = SkCodec::MakeFromData(std::move(data));
if (!codec) return false;

SkImageInfo info = codec->getInfo().makeColorType(kN32_SkColorType);
if (!bitmap->tryAllocPixels(info)) return false;

if (codec->getPixels(info, bitmap->getPixels(), bitmap->rowBytes()) == SkCodec::kSuccess)
{
//checks if rotation is needed
if (codec->getOrigin() != kTopLeft_SkEncodedOrigin)
{
SkMatrix transform = SkEncodedOriginToMatrix(codec->getOrigin(), bitmap->width(), bitmap->height());

SkPath bounds; //this is a dummy path to hold the rotated image bounds
bounds.addRect(0.0f, 0.0f, static_cast<SkScalar>(bitmap->width()), static_cast<SkScalar>(bitmap->height()));
bounds.transform(transform);

SkBitmap rotated;
if (!rotated.tryAllocPixels(info.makeWH(static_cast<int>(bounds.getBounds().width()), static_cast<int>(bounds.getBounds().height()))))
return false;

SkCanvas canvas(rotated);
canvas.concat(transform);
canvas.drawBitmap(*bitmap, 0.0f, 0.0f);
canvas.flush();

*bitmap = rotated;
}

bitmap->setImmutable();
return true;
}

return false;
}

Brian Osman

unread,
May 14, 2020, 8:28:53 AM5/14/20
to skia-d...@googlegroups.com
If you use SkImageGenerator::MakeFromEncoded, the resulting SkImageGenerator object will handle the EXIF orientation for you. You can call getInfo to get the "real" (after rotation) dimensions, and getPixels will do the rotation of the pixel data for you.

--
You received this message because you are subscribed to the Google Groups "skia-discuss" group.
To unsubscribe from this group and stop receiving emails from it, send an email to skia-discuss...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/skia-discuss/9b2723af-55db-4f63-82d9-edb71a3ce4bf%40googlegroups.com.

Bruno

unread,
May 14, 2020, 9:00:15 AM5/14/20
to skia-discuss
thanks Brian!
To unsubscribe from this group and stop receiving emails from it, send an email to skia-d...@googlegroups.com.
Reply all
Reply to author
Forward
0 new messages