@inject IJSRuntime js
@code { [Parameter] public string UploadLink { get; set; } protected override async Task OnInitializedAsync() { } protected override async Task OnAfterRenderAsync(bool firstRender) { if (firstRender) { await js.InvokeVoidAsync("startCropper"); } } async Task RemoveCropped() { await js.InvokeVoidAsync("removeCropped"); } public async Task UploadPhoto() { var photoLink = ""; return photoLink; } } @* @namespace MediaComponentLib @using Microsoft.Extensions.Localization @using Microsoft.AspNetCore.Components.Forms @inject IStringLocalizer Loc @inject IJSRuntime JSRuntime @implements IAsyncDisposable
@if (string.IsNullOrEmpty(_imageData)) {
Drop image here or click to upload
} else if (!_isCropped) {
} else {
}
@code { [Parameter] public string? UploadLink { get; set; } // Unique ID for this instance private string _uniqueId = "cropper-" + Guid.NewGuid().ToString("N"); private string? _imageData; private string? _croppedData; private bool _isCropped; private MediaJsInterop? _mediaInterop; private DotNetObjectReference? _objRef; protected override void OnInitialized() { _mediaInterop = new MediaJsInterop(JSRuntime); _objRef = DotNetObjectReference.Create(this); } private async Task HandleFileSelected(InputFileChangeEventArgs e) { try { var file = e.File; if (file == null) return; // Limit to 10MB var maxFileSize = 10L * 1024 * 1024; var stream = file.OpenReadStream(maxFileSize); using var ms = new MemoryStream(); await stream.CopyToAsync(ms); var base64 = Convert.ToBase64String(ms.ToArray()); _imageData = $"data:{file.ContentType};base64,{base64}"; _isCropped = false; } catch (Exception ex) { Console.WriteLine($"Error reading file: {ex.Message}"); } } private async Task OnImageLoaded() { if (_mediaInterop != null && !string.IsNullOrEmpty(_imageData)) { // Small delay to ensure render limits are applied by browser await Task.Delay(50); await _mediaInterop.InitCropperAsync(_uniqueId, 16.0 / 9.0, _objRef!); } } private async Task CropImage() { if (_mediaInterop != null) { _croppedData = await _mediaInterop.GetCroppedImageAsync(); await _mediaInterop.DestroyCropperAsync(); _isCropped = true; } } private async Task Reset() { if (_mediaInterop != null) await _mediaInterop.DestroyCropperAsync(); _imageData = null; _croppedData = null; _isCropped = false; } public async ValueTask DisposeAsync() { if (_mediaInterop != null) { try { await _mediaInterop.DestroyCropperAsync(); } catch { } } _objRef?.Dispose(); } } *@