Skip to content

Instantly share code, notes, and snippets.

@alanedwardes
Created December 20, 2017 00:11
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save alanedwardes/282e54302bcdffbf51de440600091ea5 to your computer and use it in GitHub Desktop.
Save alanedwardes/282e54302bcdffbf51de440600091ea5 to your computer and use it in GitHub Desktop.
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;
};
@avedapro
Copy link

avedapro commented Nov 3, 2021

I've got it built only when I set AcceptScreenshot as const method. Hope it will help everybody.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment