Instantly share code, notes, and snippets.

Embed
What would you like to do?
Unreal Engine 4 class to take and compress screenshots to a JPEG image, then raise an event with the compressed data.
// Estranged is a trade mark of Alan Edwardes.
#include "EstScreenshotTaker.h"
#include "IImageWrapper.h"
#include "IImageWrapperModule.h"
void UEstScreenshotTaker::RequestScreenshot()
{
if (GEngine == nullptr || GEngine->GameViewport == nullptr || bIsScreenshotRequested)
{
return;
}
bIsScreenshotRequested = true;
GEngine->GameViewport->OnScreenshotCaptured().AddUObject(this, &UEstScreenshotTaker::AcceptScreenshot);
FScreenshotRequest::RequestScreenshot(false);
}
void UEstScreenshotTaker::AcceptScreenshot(int32 InSizeX, int32 InSizeY, const TArray<FColor>& InImageData)
{
IImageWrapperModule& ImageWrapperModule = FModuleManager::LoadModuleChecked<IImageWrapperModule>(FName("ImageWrapper"));
TSharedPtr<IImageWrapper> ImageWrapper = ImageWrapperModule.CreateImageWrapper(EImageFormat::JPEG);
if (!ImageWrapper.IsValid())
{
bIsScreenshotRequested = false;
return;
}
if (!ImageWrapper->SetRaw(&InImageData[0], InImageData.Num() * sizeof(FColor), InSizeX, InSizeY, ERGBFormat::BGRA, 8))
{
bIsScreenshotRequested = false;
return;
}
const TArray<uint8>& CompressedImage = ImageWrapper->GetCompressed(90);
OnScreenshotJpeg.Broadcast(CompressedImage);
GEngine->GameViewport->OnScreenshotCaptured().RemoveAll(this);
bIsScreenshotRequested = false;
}
// Estranged is a trade mark of Alan Edwardes.
#pragma once
#include "EstScreenshotTaker.generated.h"
DECLARE_DYNAMIC_MULTICAST_DELEGATE_OneParam(FOnScreenshotJpeg, const TArray<uint8>&, Jpeg);
UCLASS(BlueprintType, Blueprintable)
class UEstScreenshotTaker : public UObject
{
GENERATED_BODY()
public:
UFUNCTION(BlueprintCallable, Category = Screenshot)
virtual void RequestScreenshot();
UPROPERTY(BlueprintAssignable, Category = Screenshot)
FOnScreenshotJpeg OnScreenshotJpeg;
protected:
virtual void AcceptScreenshot(int32 InSizeX, int32 InSizeY, const TArray<FColor>& InImageData);
bool bIsScreenshotRequested;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment