protected virtual void GetMapImage(RegionInfo info) { try { string regionimage = "regionImage" + info.RegionID.ToString(); regionimage = regionimage.Replace("-", ""); WebClient c = new WebClient(); string uri = "http://" + info.ExternalHostName + ":" + info.HttpPort + "/index.php?method=" + regionimage; //m_log.Debug("JPEG: " + uri); c.DownloadFile(uri, info.RegionID.ToString() + ".jpg"); Bitmap m = new Bitmap(info.RegionID.ToString() + ".jpg"); //m_log.Debug("Size: " + m.PhysicalDimension.Height + "-" + m.PhysicalDimension.Width); byte[] imageData = OpenJPEG.EncodeFromImage(m, true); AssetBase ass = new AssetBase(UUID.Random(), "region " + info.RegionID.ToString()); info.RegionSettings.TerrainImageID = ass.FullID; ass.Type = (int)AssetType.Texture; ass.Temporary = false; ass.Local = true; ass.Data = imageData; m_sceneman.CurrentOrFirstScene.AssetService.Store(ass); } catch // LEGIT: Catching problems caused by OpenJPEG p/invoke { m_log.Warn("[HGrid]: Failed getting/storing map image, because it is probably already in the cache"); } }
public byte[] WriteJpeg2000Image() { if (terrainRenderer != null) { terrainRenderer.TerrainToBitmap(mapbmp); } if (drawPrimVolume) { DrawObjectVolume(m_scene, mapbmp); } int t = Environment.TickCount; try { imageData = OpenJPEG.EncodeFromImage(mapbmp.Bitmap, true); } catch (Exception e) // LEGIT: Catching problems caused by OpenJPEG p/invoke { m_log.Error("Failed generating terrain map: " + e); } t = Environment.TickCount - t; m_log.InfoFormat("[MAPTILE] encoding of image needed {0}ms", t); return(imageData); }
private byte[] loadImage(string url) { string urll = url.ToLower(); byte[] UploadData; if (urll.EndsWith(".jpg") || urll.EndsWith(".png") || urll.EndsWith(".bmp") || urll.EndsWith(".gif")) { try { Bitmap image = GetBitmapFromURL(url); int oWidth = image.Width; int oHeight = image.Height; if (!Helper.isPowerOfTwo((uint)oWidth) || !Helper.isPowerOfTwo((uint)oHeight)) { int nWidth = Helper.nearestPowerofTwo(oWidth); int nHeight = Helper.nearestPowerofTwo(oHeight); Bitmap resized = new Bitmap(nWidth, nHeight, image.PixelFormat); Graphics graphics = Graphics.FromImage(resized); graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; graphics.DrawImage(image, 0, 0, nWidth, nHeight); image.Dispose(); image = resized; oWidth = nWidth; oHeight = nHeight; } if (oWidth > 1024 || oHeight > 1024) { int newwidth = (oWidth > 1024) ? 1024 : oWidth; int newheight = (oHeight > 1024) ? 1024 : oHeight; Bitmap resized = new Bitmap(newwidth, newheight, image.PixelFormat); Graphics graphics = Graphics.FromImage(resized); graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; graphics.DrawImage(image, 0, 0, newwidth, newheight); image.Dispose(); image = resized; } UploadData = OpenJPEG.EncodeFromImage(image, false); } catch (Exception ex) { Console.WriteLine(ex.ToString() + " SL Image Upload "); return(null); } return(UploadData); } return(null); }
private void HttpRequestReturn(IAsyncResult result) { RequestState state = (RequestState)result.AsyncState; WebRequest request = (WebRequest)state.Request; try { HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(result); if (response.StatusCode == HttpStatusCode.OK) { Bitmap image = new Bitmap(response.GetResponseStream()); Size newsize; // TODO: make this a bit less hard coded if ((image.Height < 64) && (image.Width < 64)) { newsize = new Size(32, 32); } else if ((image.Height < 128) && (image.Width < 128)) { newsize = new Size(64, 64); } else if ((image.Height < 256) && (image.Width < 256)) { newsize = new Size(128, 128); } else if ((image.Height < 512 && image.Width < 512)) { newsize = new Size(256, 256); } else if ((image.Height < 1024 && image.Width < 1024)) { newsize = new Size(512, 512); } else { newsize = new Size(1024, 1024); } Bitmap resize = new Bitmap(image, newsize); byte[] imageJ2000 = new byte[0]; try { imageJ2000 = OpenJPEG.EncodeFromImage(resize, true); } catch (Exception) { m_log.Error("[LOADIMAGEURLMODULE]: OpenJpeg Encode Failed. Empty byte data returned!"); } m_textureManager.ReturnData(state.RequestID, imageJ2000); } } catch (WebException) { } }
public byte[] WriteJpeg2000Image(string gradientmap) { byte[] imageData = null; bool drawPrimVolume = true; bool textureTerrain = false; try { IConfig startupConfig = m_config.Configs["Startup"]; drawPrimVolume = startupConfig.GetBoolean("DrawPrimOnMapTile", drawPrimVolume); textureTerrain = startupConfig.GetBoolean("TextureOnMapTile", textureTerrain); } catch { m_log.Warn("[MAPTILE]: Failed to load StartupConfig"); } if (textureTerrain) { terrainRenderer = new TexturedMapTileRenderer(); } else { terrainRenderer = new ShadedMapTileRenderer(); } terrainRenderer.Initialise(m_scene, m_config); Bitmap mapbmp = new Bitmap(256, 256); //long t = System.Environment.TickCount; //for (int i = 0; i < 10; ++i) { terrainRenderer.TerrainToBitmap(mapbmp); //} //t = System.Environment.TickCount - t; //m_log.InfoFormat("[MAPTILE] generation of 10 maptiles needed {0} ms", t); if (drawPrimVolume) { DrawObjectVolume(m_scene, mapbmp); } try { imageData = OpenJPEG.EncodeFromImage(mapbmp, true); } catch (Exception e) // LEGIT: Catching problems caused by OpenJPEG p/invoke { m_log.Error("Failed generating terrain map: " + e); } return(imageData); }
public UUID GetMapImage(UUID regionID, string imageURL, string storagePath) { if (m_AssetService == null) { m_log.DebugFormat("[GATEKEEPER SERVICE CONNECTOR]: No AssetService defined. Map tile not retrieved."); return(m_HGMapImage); } UUID mapTile = m_HGMapImage; string filename = string.Empty; try { WebClient c = new WebClient(); //m_log.Debug("JPEG: " + imageURL); string name = regionID.ToString(); filename = Path.Combine(storagePath, name + ".jpg"); m_log.DebugFormat("[GATEKEEPER SERVICE CONNECTOR]: Map image at {0}, cached at {1}", imageURL, filename); if (!File.Exists(filename)) { m_log.DebugFormat("[GATEKEEPER SERVICE CONNECTOR]: downloading..."); c.DownloadFile(imageURL, filename); } else { m_log.DebugFormat("[GATEKEEPER SERVICE CONNECTOR]: using cached image"); } byte[] imageData = null; using (Bitmap bitmap = new Bitmap(filename)) { //m_log.Debug("Size: " + m.PhysicalDimension.Height + "-" + m.PhysicalDimension.Width); imageData = OpenJPEG.EncodeFromImage(bitmap, true); } AssetBase ass = new AssetBase(UUID.Random(), "region " + name, (sbyte)AssetType.Texture, regionID.ToString()); // !!! for now //info.RegionSettings.TerrainImageID = ass.FullID; ass.Data = imageData; m_AssetService.Store(ass); // finally mapTile = ass.FullID; } catch // LEGIT: Catching problems caused by OpenJPEG p/invoke { m_log.Info("[GATEKEEPER SERVICE CONNECTOR]: Failed getting/storing map image, because it is probably already in the cache"); } return(mapTile); }
public UUID SaveBitmap(Bitmap data, bool lossless, bool temporary) { AssetBase asset = new AssetBase(UUID.Random(), "MRMDynamicImage", (sbyte)AssetType.Texture, m_scene.RegionInfo.RegionID.ToString()); asset.Data = OpenJPEG.EncodeFromImage(data, lossless); asset.Description = "MRM Image"; asset.Local = false; asset.Temporary = temporary; m_scene.AssetService.Store(asset); return(asset.FullID); }
public byte[] WriteJpeg2000Image() { try { using (Bitmap mapbmp = CreateMapTile()) return(OpenJPEG.EncodeFromImage(mapbmp, true)); } catch (Exception e) // LEGIT: Catching problems caused by OpenJPEG p/invoke { m_log.Error("Failed generating terrain map: " + e); } return(null); }
public UUID SaveBitmap(Bitmap data, bool lossless, bool temporary) { AssetBase asset = new AssetBase(UUID.Random(), "MRMDynamicImage", AssetType.Texture, m_scene.RegionInfo.RegionID) { Data = OpenJPEG.EncodeFromImage(data, lossless), Description = "MRM Image", Flags = (temporary) ? AssetFlags.Temporary : 0 }; asset.ID = m_scene.AssetService.Store(asset); return(asset.ID); }
private byte[] BlendTextures(byte[] frontImage, byte[] backImage, byte newAlpha) { ManagedImage managedImage; Image image; if (!OpenJPEG.DecodeToImage(frontImage, out managedImage, out image) || image == null) { return(null); } Bitmap image1 = new Bitmap(image); image.Dispose(); if (!OpenJPEG.DecodeToImage(backImage, out managedImage, out image) || image == null) { image1.Dispose(); return(null); } Bitmap image2 = new Bitmap(image); image.Dispose(); if (newAlpha < 255) { SetAlpha(ref image1, newAlpha); } using (Bitmap joint = MergeBitMaps(image1, image2)) { image1.Dispose(); image2.Dispose(); byte[] result = new byte[0]; try { result = OpenJPEG.EncodeFromImage(joint, true); } catch (Exception e) { m_log.ErrorFormat( "[DYNAMICTEXTUREMODULE]: OpenJpeg Encode Failed. Exception {0}{1}", e.Message, e.StackTrace); } return(result); } }
public UUID SaveBitmap(Bitmap data, bool lossless, bool temporary) { AssetBase asset = new AssetBase(); asset.FullID = UUID.Random(); asset.Data = OpenJPEG.EncodeFromImage(data, lossless); asset.Name = "MRMDynamicImage"; asset.Type = 0; asset.Description = "MRM Image"; asset.Local = false; asset.Temporary = temporary; m_scene.AssetService.Store(asset); return(asset.FullID); }
public byte[] WriteJpeg2000Image() { try { using (Bitmap mapbmp = CreateMapTile()) return(OpenJPEG.EncodeFromImage(mapbmp, true)); } catch (Exception e) { // JPEG2000 encoder failed m_log.Error("[WARP 3D IMAGE MODULE]: Failed generating terrain map: ", e); } return(null); }
static UUID UploadImage(string filename, bool lossless) { UUID newAssetID = UUID.Zero; byte[] jp2data = null; try { Bitmap image = (Bitmap)Bitmap.FromFile(filename); jp2data = OpenJPEG.EncodeFromImage(image, lossless); } catch (Exception ex) { Console.WriteLine("Failed to encode image file " + filename + ": " + ex.ToString()); return(UUID.Zero); } AutoResetEvent uploadEvent = new AutoResetEvent(false); Client.Inventory.RequestCreateItemFromAsset(jp2data, Path.GetFileNameWithoutExtension(filename), "Uploaded with importprimscript", AssetType.Texture, InventoryType.Texture, UploadFolderID, delegate(CapsClient client, long bytesReceived, long bytesSent, long totalBytesToReceive, long totalBytesToSend) { // FIXME: Do something with progress? }, delegate(bool success, string status, UUID itemID, UUID assetID) { if (success) { Console.WriteLine("Finished uploading image " + filename + ", AssetID: " + assetID.ToString()); newAssetID = assetID; } else { Console.WriteLine("Failed to upload image file " + filename + ": " + status); } uploadEvent.Set(); } ); // The images are small, 60 seconds should be plenty uploadEvent.WaitOne(1000 * 60, false); return(newAssetID); }
public void CreateMapTile(out byte[] terrain, out byte[] map) { terrain = null; map = null; Bitmap terrainBMP, mapBMP; CreateMapTile(out terrainBMP, out mapBMP); if (terrainBMP != null) { terrain = OpenJPEG.EncodeFromImage(terrainBMP, true); terrainBMP.Dispose(); } if (mapBMP != null) { map = OpenJPEG.EncodeFromImage(mapBMP, true); mapBMP.Dispose(); } }
private byte[] BlendTextures(byte[] frontImage, byte[] backImage, bool setNewAlpha, byte newAlpha, IScene scene) { Image image = scene.RequestModuleInterface <IJ2KDecoder>().DecodeToImage(frontImage); if (image != null) { Bitmap image1 = new Bitmap(image); image = scene.RequestModuleInterface <IJ2KDecoder>().DecodeToImage(backImage); if (image != null) { Bitmap image2 = new Bitmap(image); if (setNewAlpha) { SetAlpha(ref image1, newAlpha); } Bitmap joint = MergeBitMaps(image1, image2); byte[] result = new byte[0]; try { result = OpenJPEG.EncodeFromImage(joint, true); } catch (Exception) { MainConsole.Instance.Error( "[DYNAMICTEXTUREMODULE]: OpenJpeg Encode Failed. Empty byte data returned!"); } return(result); } } return(null); }
private byte[] BlendTextures(byte[] frontImage, byte[] backImage, bool setNewAlpha, byte newAlpha) { ManagedImage managedImage; Image image; if (OpenJPEG.DecodeToImage(frontImage, out managedImage, out image)) { Bitmap image1 = new Bitmap(image); if (OpenJPEG.DecodeToImage(backImage, out managedImage, out image)) { Bitmap image2 = new Bitmap(image); if (setNewAlpha) { SetAlpha(ref image1, newAlpha); } Bitmap joint = MergeBitMaps(image1, image2); byte[] result = new byte[0]; try { result = OpenJPEG.EncodeFromImage(joint, true); } catch (Exception) { m_log.Error("[DYNAMICTEXTUREMODULE]: OpenJpeg Encode Failed. Empty byte data returned!"); } return(result); } } return(null); }
public UUID GetMapImage(UUID regionID, string imageURL) { if (m_AssetService == null) { return(m_MissingTexture); } try { WebClient c = new WebClient(); //m_log.Debug("JPEG: " + imageURL); string filename = regionID.ToString(); c.DownloadFile(imageURL, filename + ".jpg"); Bitmap m = new Bitmap(filename + ".jpg"); //m_log.Debug("Size: " + m.PhysicalDimension.Height + "-" + m.PhysicalDimension.Width); byte[] imageData = OpenJPEG.EncodeFromImage(m, true); AssetBase ass = new AssetBase(UUID.Random(), "region " + filename, (sbyte)AssetType.Texture, regionID.ToString()); // !!! for now //info.RegionSettings.TerrainImageID = ass.FullID; ass.Temporary = true; ass.Local = true; ass.Data = imageData; m_AssetService.Store(ass); // finally return(ass.FullID); } catch // LEGIT: Catching problems caused by OpenJPEG p/invoke { m_log.Warn("[GATEKEEPER SERVICE CONNECTOR]: Failed getting/storing map image, because it is probably already in the cache"); } return(UUID.Zero); }
private void HttpRequestReturn(IAsyncResult result) { RequestState state = (RequestState)result.AsyncState; WebRequest request = state.Request; Stream stream = null; byte[] imageJ2000 = new byte[0]; try { HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(result); if (response != null && response.StatusCode == HttpStatusCode.OK) { stream = response.GetResponseStream(); if (stream != null) { Bitmap image = new Bitmap(stream); Size newsize; // TODO: make this a bit less hard coded if ((image.Height < 64) && (image.Width < 64)) { newsize = new Size(32, 32); } else if ((image.Height < 128) && (image.Width < 128)) { newsize = new Size(64, 64); } else if ((image.Height < 256) && (image.Width < 256)) { newsize = new Size(128, 128); } else if ((image.Height < 512 && image.Width < 512)) { newsize = new Size(256, 256); } else if ((image.Height < 1024 && image.Width < 1024)) { newsize = new Size(512, 512); } else { newsize = new Size(1024, 1024); } Bitmap resize = new Bitmap(image, newsize); try { imageJ2000 = OpenJPEG.EncodeFromImage(resize, true); } catch (Exception) { MainConsole.Instance.Error( "[LOADIMAGEURLMODULE]: OpenJpeg Encode Failed. Empty byte data returned!"); } } else { MainConsole.Instance.WarnFormat("[LOADIMAGEURLMODULE] No data returned"); } } } catch (WebException) { } catch (ArgumentException) { } finally { if (stream != null) { stream.Close(); } } MainConsole.Instance.DebugFormat("[LOADIMAGEURLMODULE] Returning {0} bytes of image data for request {1}", imageJ2000.Length, state.RequestID); m_textureManager.ReturnData(state.RequestID, imageJ2000); }
private IDynamicTexture Draw(string data, string extraParams) { // We need to cater for old scripts that didnt use extraParams neatly, they use either an integer size which represents both width and height, or setalpha // we will now support multiple comma seperated params in the form width:256,height:512,alpha:255 int width = 256; int height = 256; int alpha = 255; // 0 is transparent Color bgColor = Color.White; // Default background color char altDataDelim = ';'; char[] paramDelimiter = { ',' }; char[] nvpDelimiter = { ':' }; extraParams = extraParams.Trim(); extraParams = extraParams.ToLower(); string[] nvps = extraParams.Split(paramDelimiter); int temp = -1; foreach (string pair in nvps) { string[] nvp = pair.Split(nvpDelimiter); string name = ""; string value = ""; if (nvp[0] != null) { name = nvp[0].Trim(); } if (nvp.Length == 2) { value = nvp[1].Trim(); } switch (name) { case "width": temp = parseIntParam(value); if (temp != -1) { if (temp < 1) { width = 1; } else if (temp > 2048) { width = 2048; } else { width = temp; } } break; case "height": temp = parseIntParam(value); if (temp != -1) { if (temp < 1) { height = 1; } else if (temp > 2048) { height = 2048; } else { height = temp; } } break; case "alpha": temp = parseIntParam(value); if (temp != -1) { if (temp < 0) { alpha = 0; } else if (temp > 255) { alpha = 255; } else { alpha = temp; } } // Allow a bitmap w/o the alpha component to be created else if (value.ToLower() == "false") { alpha = 256; } break; case "bgcolor": case "bgcolour": int hex = 0; if (Int32.TryParse(value, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out hex)) { bgColor = Color.FromArgb(hex); } else { bgColor = Color.FromName(value); } break; case "altdatadelim": altDataDelim = value.ToCharArray()[0]; break; case "": // blank string has been passed do nothing just use defaults break; default: // this is all for backwards compat, all a bit ugly hopfully can be removed in future // could be either set alpha or just an int if (name == "setalpha") { alpha = 0; // set the texture to have transparent background (maintains backwards compat) } else { // this function used to accept an int on its own that represented both // width and height, this is to maintain backwards compat, could be removed // but would break existing scripts temp = parseIntParam(name); if (temp != -1) { if (temp > 1024) { temp = 1024; } if (temp < 128) { temp = 128; } width = temp; height = temp; } } break; } } Bitmap bitmap = null; Graphics graph = null; bool reuseable = false; try { // XXX: In testing, it appears that if multiple threads dispose of separate GDI+ objects simultaneously, // the native malloc heap can become corrupted, possibly due to a double free(). This may be due to // bugs in the underlying libcairo used by mono's libgdiplus.dll on Linux/OSX. These problems were // seen with both libcario 1.10.2-6.1ubuntu3 and 1.8.10-2ubuntu1. They go away if disposal is perfomed // under lock. lock (this) { if (alpha == 256) { bitmap = new Bitmap(width, height, PixelFormat.Format32bppRgb); graph = Graphics.FromImage(bitmap); using (SolidBrush bgFillBrush = new SolidBrush(bgColor)) { graph.FillRectangle(bgFillBrush, 0, 0, width, height); } } else { bitmap = new Bitmap(width, height, PixelFormat.Format32bppArgb); graph = Graphics.FromImage(bitmap); Color newbg = Color.FromArgb(alpha, bgColor); using (SolidBrush bgFillBrush = new SolidBrush(newbg)) { graph.FillRectangle(bgFillBrush, 0, 0, width, height); } } GDIDraw(data, graph, altDataDelim, out reuseable); } byte[] imageJ2000 = new byte[0]; // This code exists for testing purposes, please do not remove. // if (s_flipper) // imageJ2000 = s_asset1Data; // else // imageJ2000 = s_asset2Data; // // s_flipper = !s_flipper; try { imageJ2000 = OpenJPEG.EncodeFromImage(bitmap, true); } catch (Exception e) { m_log.ErrorFormat( "[VECTORRENDERMODULE]: OpenJpeg Encode Failed. Exception {0}{1}", e.Message, e.StackTrace); } return(new OpenSim.Region.CoreModules.Scripting.DynamicTexture.DynamicTexture( data, extraParams, imageJ2000, new Size(width, height), reuseable)); } finally { // XXX: In testing, it appears that if multiple threads dispose of separate GDI+ objects simultaneously, // the native malloc heap can become corrupted, possibly due to a double free(). This may be due to // bugs in the underlying libcairo used by mono's libgdiplus.dll on Linux/OSX. These problems were // seen with both libcario 1.10.2-6.1ubuntu3 and 1.8.10-2ubuntu1. They go away if disposal is perfomed // under lock. lock (this) { if (graph != null) { graph.Dispose(); } if (bitmap != null) { bitmap.Dispose(); } } } }
private void HttpRequestReturn(IAsyncResult result) { if (m_textureManager == null) { m_log.WarnFormat("[LOADIMAGEURLMODULE]: No texture manager. Can't function."); return; } RequestState state = (RequestState)result.AsyncState; WebRequest request = (WebRequest)state.Request; Stream stream = null; byte[] imageJ2000 = new byte[0]; Size newSize = new Size(0, 0); HttpWebResponse response = null; try { response = (HttpWebResponse)request.EndGetResponse(result); if (response != null && response.StatusCode == HttpStatusCode.OK) { stream = response.GetResponseStream(); if (stream != null) { try { using (Bitmap image = new Bitmap(stream)) { // TODO: make this a bit less hard coded if ((image.Height < 64) && (image.Width < 64)) { newSize.Width = 32; newSize.Height = 32; } else if ((image.Height < 128) && (image.Width < 128)) { newSize.Width = 64; newSize.Height = 64; } else if ((image.Height < 256) && (image.Width < 256)) { newSize.Width = 128; newSize.Height = 128; } else if ((image.Height < 512 && image.Width < 512)) { newSize.Width = 256; newSize.Height = 256; } else if ((image.Height < 1024 && image.Width < 1024)) { newSize.Width = 512; newSize.Height = 512; } else { newSize.Width = 1024; newSize.Height = 1024; } if (newSize.Width != image.Width || newSize.Height != image.Height) { using (Bitmap resize = new Bitmap(image, newSize)) imageJ2000 = OpenJPEG.EncodeFromImage(resize, false); } else { imageJ2000 = OpenJPEG.EncodeFromImage(image, false); } } } catch (Exception) { m_log.Error("[LOADIMAGEURLMODULE]: OpenJpeg Conversion Failed. Empty byte data returned!"); } } else { m_log.WarnFormat("[LOADIMAGEURLMODULE] No data returned"); } } } catch (WebException) { } catch (Exception e) { m_log.ErrorFormat("[LOADIMAGEURLMODULE]: unexpected exception {0}", e.Message); } finally { if (stream != null) { stream.Close(); } if (response != null) { if (response.StatusCode == HttpStatusCode.MovedPermanently || response.StatusCode == HttpStatusCode.Found || response.StatusCode == HttpStatusCode.SeeOther || response.StatusCode == HttpStatusCode.TemporaryRedirect) { string redirectedUrl = response.Headers["Location"]; MakeHttpRequest(redirectedUrl, state.RequestID); } else { m_log.DebugFormat("[LOADIMAGEURLMODULE]: Returning {0} bytes of image data for request {1}", imageJ2000.Length, state.RequestID); m_textureManager.ReturnData( state.RequestID, new OpenSim.Region.CoreModules.Scripting.DynamicTexture.DynamicTexture( request.RequestUri, null, imageJ2000, newSize, false)); } response.Close(); } } }
private void Draw(string data, UUID id, string extraParams) { // We need to cater for old scripts that didnt use extraParams neatly, they use either an integer size which represents both width and height, or setalpha // we will now support multiple comma seperated params in the form width:256,height:512,alpha:255 int width = 256; int height = 256; int alpha = 255; // 0 is transparent Color bgColour = Color.White; // Default background color char altDataDelim = ';'; char[] paramDelimiter = { ',' }; char[] nvpDelimiter = { ':' }; extraParams = extraParams.Trim(); extraParams = extraParams.ToLower(); string[] nvps = extraParams.Split(paramDelimiter); int temp = -1; foreach (string pair in nvps) { string[] nvp = pair.Split(nvpDelimiter); string name = ""; string value = ""; if (nvp[0] != null) { name = nvp[0].Trim(); } if (nvp.Length == 2) { value = nvp[1].Trim(); } switch (name) { case "width": temp = parseIntParam(value); if (temp != -1) { if (temp < 1) { width = 1; } else if (temp > 2048) { width = 2048; } else { width = temp; } } break; case "height": temp = parseIntParam(value); if (temp != -1) { if (temp < 1) { height = 1; } else if (temp > 2048) { height = 2048; } else { height = temp; } } break; case "alpha": temp = parseIntParam(value); if (temp != -1) { if (temp < 0) { alpha = 0; } else if (temp > 255) { alpha = 255; } else { alpha = temp; } } // Allow a bitmap w/o the alpha component to be created else if (value.ToLower() == "false") { alpha = 256; } break; case "bgcolour": int hex = 0; if (Int32.TryParse(value, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out hex)) { bgColour = Color.FromArgb(hex); } else { bgColour = Color.FromName(value); } break; case "altdatadelim": altDataDelim = value.ToCharArray()[0]; break; case "": // blank string has been passed do nothing just use defaults break; default: // this is all for backwards compat, all a bit ugly hopfully can be removed in future // could be either set alpha or just an int if (name == "setalpha") { alpha = 0; // set the texture to have transparent background (maintains backwards compat) } else { // this function used to accept an int on its own that represented both // width and height, this is to maintain backwards compat, could be removed // but would break existing scripts temp = parseIntParam(name); if (temp != -1) { if (temp > 1024) { temp = 1024; } if (temp < 128) { temp = 128; } width = temp; height = temp; } } break; } } Bitmap bitmap; if (alpha == 256) { bitmap = new Bitmap(width, height, PixelFormat.Format32bppRgb); } else { bitmap = new Bitmap(width, height, PixelFormat.Format32bppArgb); } Graphics graph = Graphics.FromImage(bitmap); // this is really just to save people filling the // background color in their scripts, only do when fully opaque if (alpha >= 255) { graph.FillRectangle(new SolidBrush(bgColour), 0, 0, width, height); } for (int w = 0; w < bitmap.Width; w++) { if (alpha <= 255) { for (int h = 0; h < bitmap.Height; h++) { bitmap.SetPixel(w, h, Color.FromArgb(alpha, bitmap.GetPixel(w, h))); } } } GDIDraw(data, graph, altDataDelim); byte[] imageJ2000 = new byte[0]; try { imageJ2000 = OpenJPEG.EncodeFromImage(bitmap, true); } catch (Exception) { m_log.Error( "[VECTORRENDERMODULE]: OpenJpeg Encode Failed. Empty byte data returned!"); } m_textureManager.ReturnData(id, imageJ2000); }
void LoadImage(ModelMaterial material) { var fname = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(FileName), material.Texture); try { string ext = System.IO.Path.GetExtension(material.Texture).ToLower(); Bitmap bitmap = null; if (ext == ".jp2" || ext == ".j2c") { material.TextureData = File.ReadAllBytes(fname); return; } if (ext == ".tga") { bitmap = LoadTGAClass.LoadTGA(fname); } else { bitmap = (Bitmap)Image.FromFile(fname); } int width = bitmap.Width; int height = bitmap.Height; // Handle resizing to prevent excessively large images and irregular dimensions if (!IsPowerOfTwo((uint)width) || !IsPowerOfTwo((uint)height) || width > 1024 || height > 1024) { var origWidth = width; var origHieght = height; width = ClosestPowerOwTwo(width); height = ClosestPowerOwTwo(height); width = width > 1024 ? 1024 : width; height = height > 1024 ? 1024 : height; Logger.Log("Image has irregular dimensions " + origWidth + "x" + origHieght + ". Resizing to " + width + "x" + height, Helpers.LogLevel.Info); Bitmap resized = new Bitmap(width, height, bitmap.PixelFormat); Graphics graphics = Graphics.FromImage(resized); graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; graphics.DrawImage(bitmap, 0, 0, width, height); bitmap.Dispose(); bitmap = resized; } material.TextureData = OpenJPEG.EncodeFromImage(bitmap, false); Logger.Log("Successfully encoded " + fname, Helpers.LogLevel.Info); } catch (Exception ex) { Logger.Log("Failed loading " + fname + ": " + ex.Message, Helpers.LogLevel.Warning); } }
private void LoadImage() { if (String.IsNullOrEmpty(FileName)) { return; } string extension = System.IO.Path.GetExtension(FileName).ToLower(); Bitmap bitmap = null; try { if (extension == ".jp2" || extension == ".j2c") { Image image; ManagedImage managedImage; // Upload JPEG2000 images untouched UploadData = System.IO.File.ReadAllBytes(FileName); OpenJPEG.DecodeToImage(UploadData, out managedImage, out image); bitmap = (Bitmap)image; Logger.Log("Loaded raw JPEG2000 data " + FileName, Helpers.LogLevel.Info, Client); } else { if (extension == ".tga") { bitmap = LoadTGAClass.LoadTGA(FileName); } else { bitmap = (Bitmap)System.Drawing.Image.FromFile(FileName); } Logger.Log("Loaded image " + FileName, Helpers.LogLevel.Info, Client); int oldwidth = bitmap.Width; int oldheight = bitmap.Height; if (!IsPowerOfTwo((uint)oldwidth) || !IsPowerOfTwo((uint)oldheight)) { Logger.Log("Image has irregular dimensions " + oldwidth + "x" + oldheight + ", resizing to 256x256", Helpers.LogLevel.Info, Client); Bitmap resized = new Bitmap(256, 256, bitmap.PixelFormat); Graphics graphics = Graphics.FromImage(resized); graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; graphics.DrawImage(bitmap, 0, 0, 256, 256); bitmap.Dispose(); bitmap = resized; oldwidth = 256; oldheight = 256; } // Handle resizing to prevent excessively large images if (oldwidth > 1024 || oldheight > 1024) { int newwidth = (oldwidth > 1024) ? 1024 : oldwidth; int newheight = (oldheight > 1024) ? 1024 : oldheight; Logger.Log("Image has oversized dimensions " + oldwidth + "x" + oldheight + ", resizing to " + newwidth + "x" + newheight, Helpers.LogLevel.Info, Client); Bitmap resized = new Bitmap(newwidth, newheight, bitmap.PixelFormat); Graphics graphics = Graphics.FromImage(resized); graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; graphics.DrawImage(bitmap, 0, 0, newwidth, newheight); bitmap.Dispose(); bitmap = resized; } Logger.Log("Encoding image...", Helpers.LogLevel.Info, Client); UploadData = OpenJPEG.EncodeFromImage(bitmap, chkLossless.Checked); Logger.Log("Finished encoding", Helpers.LogLevel.Info, Client); //System.IO.File.WriteAllBytes("out.jp2", UploadData); } } catch (Exception ex) { UploadData = null; cmdSave.Enabled = false; cmdUpload.Enabled = false; MessageBox.Show(ex.ToString(), "SL Image Upload", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } picPreview.Image = bitmap; lblSize.Text = Math.Round((double)UploadData.Length / 1024.0d, 2) + "KB"; prgUpload.Maximum = UploadData.Length; cmdSave.Enabled = true; if (Client.Network.Connected) { cmdUpload.Enabled = true; } }
private byte[] LoadImage(string fileName) { string lowfilename = fileName.ToLower(CultureInfo.CurrentCulture); Bitmap bitmap = null; try { if (lowfilename.EndsWith(".jp2", StringComparison.CurrentCultureIgnoreCase) || lowfilename.EndsWith(".j2c", StringComparison.CurrentCultureIgnoreCase)) { Image image; ManagedImage managedImage; // Upload JPEG2000 images untouched ImgUp = System.IO.File.ReadAllBytes(fileName); OpenJPEG.DecodeToImage(ImgUp, out managedImage, out image); bitmap = (Bitmap)image; } else { if (lowfilename.EndsWith(".tga", StringComparison.CurrentCultureIgnoreCase)) { bitmap = LoadTGAClass.LoadTGA(fileName); } else { bitmap = (Bitmap)System.Drawing.Image.FromFile(fileName); } int oldwidth = bitmap.Width; int oldheight = bitmap.Height; if (!IsPowerOfTwo((uint)oldwidth) || !IsPowerOfTwo((uint)oldheight)) { Bitmap resized = new Bitmap(256, 256, bitmap.PixelFormat); Graphics graphics = Graphics.FromImage(resized); graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; graphics.DrawImage(bitmap, 0, 0, 256, 256); bitmap.Dispose(); bitmap = resized; oldwidth = 256; oldheight = 256; } // Handle resizing to prevent excessively large images if (oldwidth > 1024 || oldheight > 1024) { int newwidth = (oldwidth > 1024) ? 1024 : oldwidth; int newheight = (oldheight > 1024) ? 1024 : oldheight; Bitmap resized = new Bitmap(newwidth, newheight, bitmap.PixelFormat); Graphics graphics = Graphics.FromImage(resized); graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; graphics.DrawImage(bitmap, 0, 0, newwidth, newheight); bitmap.Dispose(); bitmap = resized; } ImgUp = OpenJPEG.EncodeFromImage(bitmap, false); } } catch (Exception ex) { label3.Text = ex.ToString() + " SL Image Upload "; return(null); } return(ImgUp); }
public void LoadImage(string fname) { FileName = fname; if (String.IsNullOrEmpty(FileName)) { return; } txtStatus.AppendText("Loading...\n"); string extension = Path.GetExtension(FileName).ToLower(); try { Bitmap bitmap = null; switch (extension) { case ".jp2": case ".j2c": Image image; ManagedImage managedImage; // Upload JPEG2000 images untouched UploadData = File.ReadAllBytes(FileName); OpenJPEG.DecodeToImage(UploadData, out managedImage, out image); bitmap = (Bitmap)image; txtStatus.AppendText("Loaded raw JPEG2000 data " + FileName + "\n"); break; case ".tga": bitmap = LoadTGAClass.LoadTGA(FileName); break; default: bitmap = (Bitmap)Image.FromFile(FileName); break; } txtStatus.AppendText("Loaded image " + FileName + "\n"); int width = bitmap.Width; int height = bitmap.Height; // Handle resizing to prevent excessively large images and irregular dimensions if (!IsPowerOfTwo((uint)width) || !IsPowerOfTwo((uint)height) || width > 1024 || height > 1024) { txtStatus.AppendText("Image has irregular dimensions " + width + "x" + height + "\n"); width = ClosestPowerOwTwo(width); height = ClosestPowerOwTwo(height); width = width > 1024 ? 1024 : width; height = height > 1024 ? 1024 : height; txtStatus.AppendText("Resizing to " + width + "x" + height + "\n"); Bitmap resized = new Bitmap(width, height, bitmap.PixelFormat); Graphics graphics = Graphics.FromImage(resized); graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; graphics.DrawImage(bitmap, 0, 0, width, height); bitmap.Dispose(); bitmap = resized; } txtStatus.AppendText("Encoding image...\n"); UploadData = OpenJPEG.EncodeFromImage(bitmap, chkLossless.Checked); txtStatus.AppendText("Finished encoding.\n"); ImageLoaded = true; UpdateButtons(); txtAssetID.Text = UUID.Zero.ToString(); pbPreview.Image = bitmap; lblSize.Text = string.Format("{0}x{1} {2} KB", bitmap.Width, bitmap.Height, Math.Round((double)UploadData.Length / 1024.0d, 2)); } catch (Exception ex) { UploadData = null; btnSave.Enabled = false; btnUpload.Enabled = false; txtStatus.AppendText(string.Format("Failed to load the image:\n{0}\n", ex.Message)); } }
private Byte[] GenerateOverlay() { Bitmap overlay = new Bitmap(m_scene.RegionInfo.RegionSizeX, m_scene.RegionInfo.RegionSizeY); bool[,] saleBitmap = new bool[m_scene.RegionInfo.RegionSizeX / 4, m_scene.RegionInfo.RegionSizeX / 4]; bool[,] auctionBitmap = new bool[m_scene.RegionInfo.RegionSizeX / 4, m_scene.RegionInfo.RegionSizeX / 4]; for (int x = 0; x < m_scene.RegionInfo.RegionSizeX / 4; x++) { for (int y = 0; y < m_scene.RegionInfo.RegionSizeY / 4; y++) { saleBitmap[x, y] = false; auctionBitmap[x, y] = false; } } bool landForSale = false; List <ILandObject> parcels = m_scene.RequestModuleInterface <IParcelManagementModule>().AllParcels(); Color background = Color.FromArgb(0, 0, 0, 0); SolidBrush transparent = new SolidBrush(background); Graphics g = Graphics.FromImage(overlay); g.FillRectangle(transparent, 0, 0, m_scene.RegionInfo.RegionSizeX, m_scene.RegionInfo.RegionSizeY); SolidBrush yellow = new SolidBrush(Color.FromArgb(255, 249, 223, 9)); SolidBrush purple = new SolidBrush(Color.Purple); foreach (ILandObject land in parcels) { // MainConsole.Instance.DebugFormat("[WORLD MAP]: Parcel {0} flags {1}", land.LandData.Name, land.LandData.Flags); if ((land.LandData.Flags & (uint)ParcelFlags.ForSale) != 0) { landForSale = true; for (int x = 0; x < m_scene.RegionInfo.RegionSizeX / 4; x++) { for (int y = 0; y < m_scene.RegionInfo.RegionSizeY / 4; y++) { if (land.ContainsPoint(x, y)) { if (land.LandData.AuctionID > 0) { auctionBitmap[x, y] = true; } else { saleBitmap[x, y] = true; } } } } } } if (!landForSale) { return(null); } for (int x = 0; x < m_scene.RegionInfo.RegionSizeX / 4; x++) { for (int y = 0; y < m_scene.RegionInfo.RegionSizeY / 4; y++) { if (saleBitmap[x, y]) { g.FillRectangle(yellow, x * 4, m_scene.RegionInfo.RegionSizeY - 4 - (y * 4), 4, 4); } if (auctionBitmap[x, y]) { g.FillRectangle(purple, x * 4, m_scene.RegionInfo.RegionSizeY - 4 - (y * 4), 4, 4); } } } try { return(OpenJPEG.EncodeFromImage(overlay, true)); } catch (Exception) { return(null); } }
public void PaintEffect(ITerrainChannel map, UUID userID, float rx, float ry, float rz, float strength, float duration, float BrushSize, List <IScene> scene) { if (locked) { return; } locked = true; strength = TerrainUtil.MetersToSphericalStrength(BrushSize); int x, y; int xFrom = (int)(rx - BrushSize + 0.5); int xTo = (int)(rx + BrushSize + 0.5) + 1; int yFrom = (int)(ry - BrushSize + 0.5); int yTo = (int)(ry + BrushSize + 0.5) + 1; if (xFrom < 0) { xFrom = 0; } if (yFrom < 0) { yFrom = 0; } if (xTo > map.Width) { xTo = map.Width; } if (yTo > map.Height) { yTo = map.Height; } //ONLY get cached assets, since this is a local asset ONLY AssetBase paintAsset = map.Scene.AssetService.Get(map.Scene.RegionInfo.RegionSettings.PaintableTerrainTexture.ToString()); if (paintAsset == null) { paintAsset = new AssetBase(map.Scene.RegionInfo.RegionSettings.PaintableTerrainTexture, "PaintableTerrainTexture-" + map.Scene.RegionInfo.RegionID, AssetType.Texture, UUID.Zero) { Flags = AssetFlags.Deletable }; AssetBase defaultTexture = map.Scene.AssetService.Get(RegionSettings.DEFAULT_TERRAIN_TEXTURE_2.ToString()); //Nice grass if (defaultTexture == null) { //Erm... what to do! return; } paintAsset.Data = defaultTexture.Data; //Eventually we need to replace this with an interpolation of the existing textures! } AssetBase textureToApply = map.Scene.AssetService.Get(m_textureToPaint.ToString()); //The texture the client wants to paint if (textureToApply == null) { return; } Image paintiTexture = map.Scene.RequestModuleInterface <IJ2KDecoder>().DecodeToImage(paintAsset.Data); if (paintiTexture == null) { return; } Image textureToAddiTexture = map.Scene.RequestModuleInterface <IJ2KDecoder>().DecodeToImage(textureToApply.Data); if (textureToAddiTexture == null) { paintiTexture.Dispose(); return; } FastBitmap paintTexture = new FastBitmap((Bitmap)paintiTexture); FastBitmap textureToAddTexture = new FastBitmap((Bitmap)textureToAddiTexture); paintTexture.LockBitmap(); textureToAddTexture.LockBitmap(); // blend in map for (x = xFrom; x < xTo; x++) { for (y = yFrom; y < yTo; y++) { if (!map.Scene.Permissions.CanTerraformLand(userID, new Vector3(x, y, 0))) { continue; } Color c = textureToAddTexture.GetPixel( (int)((x / (float)map.Scene.RegionInfo.RegionSizeX * textureToAddiTexture.Width)), (int)((y / (float)map.Scene.RegionInfo.RegionSizeX) * textureToAddiTexture.Height)); paintTexture.SetPixel((int)((x / (float)map.Scene.RegionInfo.RegionSizeX) * paintiTexture.Width), (int)((y / (float)map.Scene.RegionInfo.RegionSizeX) * paintiTexture.Height), c); } } map.Scene.AssetService.Delete(paintAsset.ID); paintTexture.UnlockBitmap(); textureToAddTexture.UnlockBitmap(); paintAsset.Data = OpenJPEG.EncodeFromImage(paintTexture.Bitmap(), false); paintAsset.Flags = AssetFlags.Deletable; map.Scene.RegionInfo.RegionSettings.PaintableTerrainTexture = UUID.Random(); paintAsset.ID = map.Scene.RegionInfo.RegionSettings.PaintableTerrainTexture; paintAsset.ID = map.Scene.AssetService.Store(paintAsset); map.Scene.RequestModuleInterface <IEstateModule>().sendRegionHandshakeToAll(); locked = false; }
public void ShadeWorld(string[] cmd) { if (MainConsole.Instance.ConsoleScene == null) { MainConsole.Instance.Output("Select a scene first"); return; } bool greyScale = MainConsole.Instance.Prompt("Greyscale (yes or no)?").ToLower() == "yes"; int R = 0; int G = 0; int B = 0; float percent = 0; if (!greyScale) { R = int.Parse(MainConsole.Instance.Prompt("R color (0 - 255)")); G = int.Parse(MainConsole.Instance.Prompt("G color (0 - 255)")); B = int.Parse(MainConsole.Instance.Prompt("B color (0 - 255)")); percent = float.Parse(MainConsole.Instance.Prompt("Percent to merge in the shade (0 - 100)")); } if (percent > 1) { percent /= 100; } Color shader = Color.FromArgb(R, G, B); IJ2KDecoder j2kDecoder = MainConsole.Instance.ConsoleScene.RequestModuleInterface <IJ2KDecoder>(); ISceneEntity[] entities = MainConsole.Instance.ConsoleScene.Entities.GetEntities(); foreach (ISceneEntity entity in entities) { foreach (ISceneChildEntity child in entity.ChildrenEntities()) { UUID[] textures = GetTextures(child.Shape.Textures); foreach (UUID t in textures) { if (m_previouslyConverted.ContainsKey(t)) { child.Shape.Textures = SetTexture(child.Shape, m_previouslyConverted[t], t); } else { AssetBase a = MainConsole.Instance.ConsoleScene.AssetService.Get(t.ToString()); if (a != null) { Bitmap texture = (Bitmap)j2kDecoder.DecodeToImage(a.Data); if (texture == null) { continue; } a.ID = UUID.Random(); texture = Shade(texture, shader, percent, greyScale); a.Data = OpenJPEG.EncodeFromImage(texture, false); texture.Dispose(); a.ID = MainConsole.Instance.ConsoleScene.AssetService.Store(a); child.Shape.Textures = SetTexture(child.Shape, a.ID, t); m_previouslyConverted.Add(t, a.ID); m_revertConverted.Add(a.ID, t); } } } } } }
private void HttpRequestReturn(IAsyncResult result) { RequestState state = (RequestState)result.AsyncState; WebRequest request = (WebRequest)state.Request; Stream stream = null; byte[] imageJ2000 = new byte[0]; Size newSize = new Size(0, 0); try { HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(result); if (response != null && response.StatusCode == HttpStatusCode.OK) { stream = response.GetResponseStream(); if (stream != null) { try { Bitmap image = new Bitmap(stream); // TODO: make this a bit less hard coded if ((image.Height < 64) && (image.Width < 64)) { newSize.Width = 32; newSize.Height = 32; } else if ((image.Height < 128) && (image.Width < 128)) { newSize.Width = 64; newSize.Height = 64; } else if ((image.Height < 256) && (image.Width < 256)) { newSize.Width = 128; newSize.Height = 128; } else if ((image.Height < 512 && image.Width < 512)) { newSize.Width = 256; newSize.Height = 256; } else if ((image.Height < 1024 && image.Width < 1024)) { newSize.Width = 512; newSize.Height = 512; } else { newSize.Width = 1024; newSize.Height = 1024; } using (Bitmap resize = new Bitmap(image, newSize)) { imageJ2000 = OpenJPEG.EncodeFromImage(resize, true); } } catch (Exception) { m_log.Error("[LOADIMAGEURLMODULE]: OpenJpeg Conversion Failed. Empty byte data returned!"); } } else { m_log.WarnFormat("[LOADIMAGEURLMODULE] No data returned"); } } } catch (WebException) { } finally { if (stream != null) { stream.Close(); } } m_log.DebugFormat("[LOADIMAGEURLMODULE]: Returning {0} bytes of image data for request {1}", imageJ2000.Length, state.RequestID); m_textureManager.ReturnData( state.RequestID, new OpenSim.Region.CoreModules.Scripting.DynamicTexture.DynamicTexture( request.RequestUri, null, imageJ2000, newSize, false)); }
private byte[] LoadImage(string fileName) { byte[] UploadData; string lowfilename = fileName.ToLower(); Bitmap bitmap = null; try { if (lowfilename.EndsWith(".jp2") || lowfilename.EndsWith(".j2c")) { Image image; ManagedImage managedImage; // Upload JPEG2000 images untouched UploadData = System.IO.File.ReadAllBytes(fileName); OpenJPEG.DecodeToImage(UploadData, out managedImage, out image); bitmap = (Bitmap)image; } else { if (lowfilename.EndsWith(".tga")) { bitmap = LoadTGAClass.LoadTGA(fileName); } else { bitmap = (Bitmap)Image.FromFile(fileName); } int oldwidth = bitmap.Width; int oldheight = bitmap.Height; if (!IsPowerOfTwo((uint)oldwidth) || !IsPowerOfTwo((uint)oldheight)) { Bitmap resized = new Bitmap(256, 256, bitmap.PixelFormat); Graphics graphics = Graphics.FromImage(resized); graphics.SmoothingMode = SmoothingMode.HighQuality; graphics.InterpolationMode = InterpolationMode.HighQualityBicubic; graphics.DrawImage(bitmap, 0, 0, 256, 256); bitmap.Dispose(); bitmap = resized; oldwidth = 256; oldheight = 256; } // Handle resizing to prevent excessively large images if (oldwidth > 1024 || oldheight > 1024) { int newwidth = (oldwidth > 1024) ? 1024 : oldwidth; int newheight = (oldheight > 1024) ? 1024 : oldheight; Bitmap resized = new Bitmap(newwidth, newheight, bitmap.PixelFormat); Graphics graphics = Graphics.FromImage(resized); graphics.SmoothingMode = SmoothingMode.HighQuality; graphics.InterpolationMode = InterpolationMode.HighQualityBicubic; graphics.DrawImage(bitmap, 0, 0, newwidth, newheight); bitmap.Dispose(); bitmap = resized; } UploadData = OpenJPEG.EncodeFromImage(bitmap, false); } } catch (Exception ex) { Console.WriteLine(ex.ToString() + " SL Image Upload "); return(null); } return(UploadData); }