Skip to content

Instantly share code, notes, and snippets.

@ricaun
Created March 18, 2024 21:17
Show Gist options
  • Save ricaun/2e8b472f8680ed896d8bce8bf613b094 to your computer and use it in GitHub Desktop.
Save ricaun/2e8b472f8680ed896d8bce8bf613b094 to your computer and use it in GitHub Desktop.
BitmapSource Dpi Extension to scale dpi image to fit in the 32x32 inside Revit
using Autodesk.Revit.UI;
using ricaun.Revit.UI;
namespace RevitAddin.Forum.Revit
{
[AppLoader]
public class AppScale : IExternalApplication
{
private RibbonPanel ribbonPanel;
public Result OnStartup(UIControlledApplication application)
{
ribbonPanel = application.CreatePanel("Image Scale Dpi");
ribbonPanel.CreatePushButton<Commands.Command>("512").LargeImage = "Resources/DWG512.png".GetBitmapSource().ScaleDpi32();
ribbonPanel.CreatePushButton<Commands.Command>("96").LargeImage = "Resources/DWG96.png".GetBitmapSource().ScaleDpi32();
ribbonPanel.CreatePushButton<Commands.Command>("32").LargeImage = "Resources/DWG32.png".GetBitmapSource().ScaleDpi32();
return Result.Succeeded;
}
public Result OnShutdown(UIControlledApplication application)
{
ribbonPanel?.Remove();
return Result.Succeeded;
}
}
}
using System.Windows.Media;
using System.Windows.Media.Imaging;
namespace RevitAddin.Forum.Revit
{
public static class BitmapSourceDpiExtension
{
const int ICON_LARGE = 32;
const int DEFAULT_DPI = 96;
public static BitmapSource ScaleDpi32(this BitmapSource bitmapSource)
{
// Image properties
int imageSize = bitmapSource.PixelWidth;
PixelFormat imageFormat = bitmapSource.Format;
int imageBytePerPixel = (int)(bitmapSource.Format.BitsPerPixel / 8);
BitmapPalette palette = bitmapSource.Palette;
// Adjustments
int adjustedIconSize = ICON_LARGE;
int adjustedDpi = DEFAULT_DPI;
double screenScaling = (double)imageSize / adjustedIconSize;
if (screenScaling < 1.0) screenScaling = 1.0;
// Copying pixel data
int stride = imageSize * imageBytePerPixel;
int arraySize = stride * imageSize;
byte[] imageData = new byte[arraySize];
bitmapSource.CopyPixels(imageData, stride, 0);
// Scaling
int scaledSize = (int)(adjustedIconSize * screenScaling);
int scaledDpi = (int)(adjustedDpi * screenScaling);
//System.Console.WriteLine($"Size:{scaledSize} Dpi:{scaledDpi}");
BitmapSource result = BitmapSource.Create(scaledSize, scaledSize,
scaledDpi, scaledDpi,
imageFormat,
palette,
imageData,
stride);
return result;
}
}
}
@ricaun
Copy link
Author

ricaun commented Mar 18, 2024

The AppScale.cs uses the package ricaun.Revit.UI to help convert the image to BitmapSource.

The BitmapSourceDpiExtension.cs is based on the pyRevit implementation.

RevitAPI Forum: https://forums.autodesk.com/t5/revit-api-forum/scale-create-images-for-button-icons/td-p/12646642

@ricaun
Copy link
Author

ricaun commented Mar 18, 2024

Revit Image Scale Dpi

DWG512DWG96DWG32

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