Search Results

Search found 258 results on 11 pages for 'drawimage'.

Page 10/11 | < Previous Page | 6 7 8 9 10 11  | Next Page >

  • c# video equivalent to image.fromstream? Or changing the scope of the following script to allow vide

    - by Daniel
    The following is a part of an upload class in a c# script. I'm a php programmer, I've never messed with c# much but I'm trying to learn. This upload script will not handle anything except images, I need to adapt this class to handle other types of media also, or rewrite it all together. If I'm correct, I realize that using (Image image = Image.FromStream(file.InputStream)) basically says that the scope of the following is Image, only an image can be used or the object is discarded? And also that the variable image is being created from an Image from the file stream, which I understand to be, like... the $_FILES array in php? I dunno, I don't really care about making thumbnails right now either way, so if this can be taken out and still process the upload I'm totally cool with that, I just haven't had any luck getting this thing to take anything but images, even when commenting out that whole part of the class... protected void Page_Load(object sender, EventArgs e) { string dir = Path.Combine(Request.PhysicalApplicationPath, "files"); if (Request.Files.Count == 0) { // No files were posted Response.StatusCode = 500; } else { try { // Only one file at a time is posted HttpPostedFile file = Request.Files[0]; // Size limit 100MB if (file.ContentLength > 102400000) { // File too large Response.StatusCode = 500; } else { string id = Request.QueryString["userId"]; string[] folders = userDir(id); foreach (string folder in folders) { dir = Path.Combine(dir, folder); if (!Directory.Exists(dir)) Directory.CreateDirectory(dir); } string path = Path.Combine(dir, String.Concat(Request.QueryString["batchId"], "_", file.FileName)); file.SaveAs(path); // Create thumbnail int dot = path.LastIndexOf('.'); string thumbpath = String.Concat(path.Substring(0, dot), "_thumb", path.Substring(dot)); using (Image image = Image.FromStream(file.InputStream)) { // Find the ratio that will create maximum height or width of 100px. double ratio = Math.Max(image.Width / 100.0, image.Height / 100.0); using (Image thumb = new Bitmap(image, new Size((int)Math.Round(image.Width / ratio), (int)Math.Round(image.Height / ratio)))) { using (Graphics graphic = Graphics.FromImage(thumb)) { // Make sure thumbnail is not crappy graphic.SmoothingMode = SmoothingMode.HighQuality; graphic.InterpolationMode = InterpolationMode.High; graphic.CompositingQuality = CompositingQuality.HighQuality; // JPEG ImageCodecInfo codec = ImageCodecInfo.GetImageEncoders()[1]; // 90% quality EncoderParameters encode = new EncoderParameters(1); encode.Param[0] = new EncoderParameter(Encoder.Quality, 90L); // Resize graphic.DrawImage(image, new Rectangle(0, 0, thumb.Width, thumb.Height)); // Save thumb.Save(thumbpath, codec, encode); } } } // Success Response.StatusCode = 200; } } catch { // Something went wrong Response.StatusCode = 500; } } }

    Read the article

  • How can I set an image for background of GUI interface?

    - by enriched
    hey everyone, im having some troubles displaying the background image for a GUI interface in java. Here is what i have at the moment, and with current stage of code it shows default(gray) background. import javax.swing.*; import java.awt.event.*; import java.util.Scanner; import java.awt.*; import java.io.File; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.IOException; ////////////////////////////////// // 3nriched Games Presents: // // MIPS The Mouse!! // ////////////////////////////////// public class mipsMouseGUI extends JFrame implements ActionListener { private static String ThePDub = ("mouse"); //the password JPasswordField pass; JPanel panel; JButton btnEnter; JLabel lblpdub; public mipsMouseGUI() { BufferedImage image = null; try { //attempts to read picture from the folder image = ImageIO.read(getClass().getResource("/mousepics/mousepic.png")); } catch (IOException e) { //catches exceptions e.printStackTrace(); } ImagePanel panel = new ImagePanel(new ImageIcon("/mousepics/neonglowOnwill.png").getImage()); setIconImage(image); //sets icon picture setTitle("Mips The Mouse Login"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); pass = new JPasswordField(5); //sets password length to 5 pass.setEchoChar('@'); //hide characters as @ symbol pass.addActionListener(this); //adds action listener add(panel); //adds panel to frame btnEnter = new JButton("Enter"); //creates a button btnEnter.addActionListener(this);// Register the action listener. lblpdub = new JLabel(" Your Password: "); // label that says enter password panel.add(lblpdub, BorderLayout.CENTER);// adds label and inputbox panel.add(pass, BorderLayout.CENTER); // to panel and sets location panel.add(btnEnter, BorderLayout.CENTER); //adds button to panel pack(); // packs controls and setLocationRelativeTo(null); // Implicit "this" if inside JFrame constructor. setVisible(true);// makes them visible (duh) } public void actionPerformed(ActionEvent a) { Object source = a.getSource(); //char array that holds password char[] passy = pass.getPassword(); //characters array to string String p = new String(passy); //determines if user entered correct password if(p.equals(ThePDub)) { JOptionPane.showMessageDialog(null, "Welcome beta user: USERNAME."); } else JOptionPane.showMessageDialog(null, "You have enter an incorrect password. Please try again."); } public class ImagePanel extends JPanel { private BufferedImage img; public ImagePanel(String img) { this(new ImageIcon(img).getImage()); } public ImagePanel(Image img) { Dimension size = new Dimension(img.getWidth(null), img.getHeight(null)); } public void paintComponent(Graphics g) { g.drawImage(img, 0, 0, null); } } }

    Read the article

  • Error:A generic error occurred in GDI+

    - by sanfra1983
    Hi, I created a web project on the server, and when I upload an image shows me the error Error: A generic error occurred in GDI +. I have read many links on the net that talk about this issue, and although I made the changes, nothing went wrong. I was thinking if the case is not an issue of permissions to folders. In fact I have two folders one inside the other. This is the code to resize the image: public Bitmaps ResizeImage (Stream stream, int? width, int? height) ( System.Drawing.Bitmap bmpOut = null; const int defaultWidth = 800; const int defaultHeight = 600; int width = lnWidth == null? defaultWidth: (int) width; int height = lnHeight == null? defaultHeight: (int) height; try ( LoBMP bitmap = new Bitmap (stream); ImageFormat loFormat = loBMP.RawFormat; decimal lnRatio; lnNewWidth int = 0; lnNewHeight int = 0; if (loBMP.Width <& & lnWidth loBMP.Height <lnHeight) ( loBMP return; ) if (loBMP.Width> loBMP.Height) ( lnRatio = (decimal) lnWidth / loBMP.Width; lnNewWidth = lnWidth; decimal = lnTemp loBMP.Height lnRatio *; lnNewHeight = (int) lnTemp; ) else ( lnRatio = (decimal) lnHeight / loBMP.Height; lnNewHeight = lnHeight; decimal = lnTemp loBMP.Width lnRatio *; lnNewWidth = (int) lnTemp; ) bmpOut = new Bitmap (lnNewWidth, lnNewHeight); Graphics g = Graphics.FromImage (bmpOut); g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; g.FillRectangle (Brushes.White, 0, 0, lnNewWidth, lnNewHeight); g.DrawImage (loBMP, 0, 0, lnNewWidth, lnNewHeight); loBMP.Dispose (); ) catch ( return null; ) bmpOut return; ) and this is the code that I insert in the codebehind: string filepath = AppDomain.CurrentDomain.BaseDirectory + img_veterinario / "; string = filepathM AppDomain.CurrentDomain.BaseDirectory + img_veterinario / img_veterinarioM; Reseize Reseize R = new (); Bitmap = photosFileOriginal r.ResizeImage (fucasiclinici.PostedFile.InputStream, 400, 400); Bitmap = photosFileMiniatura r.ResizeImage (fucasiclinici.PostedFile.InputStream, 72, 72); String filename = Path.GetFileName (fucasiclinici.PostedFile.FileName); photosFileOriginal.Save (Path.Combine (filepath, filename)); photosFileMiniatura.Save (Path.Combine (filepathM, filename)); Can you help me? Thanks

    Read the article

  • Using Lightbox with _Screen

    Although, I have to admit that I discovered Bernard Bout's ideas and concepts about implementing a lightbox in Visual FoxPro quite a while ago, there was no "spare" time in active projects that allowed me to have a closer look into his solution(s). Luckily, these days I received a demand to focus a little bit more on this. This article describes the steps about how to integrate and make use of Bernard's lightbox class in combination with _Screen in Visual FoxPro. The requirement in this project was to be able to visually lock the whole application (_Screen area) and guide the user to an information that should not be ignored easily. Depending on the importance any current user activity should be interrupted and focus put onto the notification. Getting the "meat", eh, source code Please check out Bernard's blog on Foxite directly in order to get the latest and greatest version. As time of writing this article I use version 6.0 as described in this blog entry: The Fastest Lightbox Ever The Lightbox class is sub-classed from the imgCanvas class from the GdiPlusX project on VFPx and therefore you need to have the source code of GdiPlusX as well, and integrate it into your development environment. The version I use is available here: Release GDIPlusX 1.20 As soon as you open the bbGdiLightbox class the first it, VFP might ask you to update the reference to the gdiplusx.vcx. As we have the sources, no problem and you have access to Bernard's code. The class itself is pretty easy to understand, some properties that you do not need to change and three methods: Setup(), ShowLightbox() and BeforeDraw() The challenge - _Screen or not? Reading Bernard's article about the fastest lightbox ever, he states the following: "The class will only work on a form. It will not support any other containers" Really? And what about _Screen? Isn't that a form class, too? Yes, of course it is but nonetheless trying to use _Screen directly will fail. Well, let's have look at the code to see why: WITH This .Left = 0 .Top = 0 .Height = ThisForm.Height .Width = ThisForm.Width .ZOrder(0) .Visible = .F.ENDWITH During the setup of the lightbox as well as while capturing the image as replacement for your forms and controls, the object reference Thisform is used. Which is a little bit restrictive to my opinion but let's continue. The second issue lies in the method ShowLightbox() and introduced by the call of .Bitmap.FromScreen(): Lparameters tlVisiblilty* tlVisiblilty - show or hide (T/F)* grab a screen dump with controlsIF tlVisiblilty Local loCaptureBmp As xfcBitmap Local lnTitleHeight, lnLeftBorder, lnTopBorder, lcImage, loImage lnTitleHeight = IIF(ThisForm.TitleBar = 1,Sysmetric(9),0) lnLeftBorder = IIF(ThisForm.BorderStyle < 2,0,Sysmetric(3)) lnTopBorder = IIF(ThisForm.BorderStyle < 2,0,Sysmetric(4)) With _Screen.System.Drawing loCaptureBmp = .Bitmap.FromScreen(ThisForm.HWnd,; lnLeftBorder,; lnTopBorder+lnTitleHeight,; ThisForm.Width ,; ThisForm.Height) ENDWITH * save it to a property This.capturebmp = loCaptureBmp ThisForm.SetAll("Visible",.F.) This.DraW() This.Visible = .T.ELSE ThisForm.SetAll("Visible",.T.) This.Visible = .F.ENDIF My first trials in using the class ended in an exception - GdiPlusError:OutOfMemory - thrown by the Bitmap object. Frankly speaking, this happened mainly because of my lack of knowledge about GdiPlusX. After reading some documentation, especially about the FromScreen() method I experimented a little bit. Capturing the visible area of _Screen actually was not the real problem but the dimensions I specified for the bitmap. The modifications - step by step First of all, it is to get rid of restrictive object references on Thisform and to change them into either This.Parent or more generic into This.oForm (even better: This.oControl). The Lightbox.Setup() method now sets the necessary object reference like so: *====================================================================* Initial setup* Default value: This.oControl = "This.Parent"* Alternative: This.oControl = "_Screen"*====================================================================With This .oControl = Evaluate(.oControl) If Vartype(.oControl) == T_OBJECT .Anchor = 0 .Left = 0 .Top = 0 .Width = .oControl.Width .Height = .oControl.Height .Anchor = 15 .ZOrder(0) .Visible = .F. EndIfEndwith Also, based on other developers' comments in Bernard articles on his lightbox concept and evolution I found the source code to handle the differences between a form and _Screen and goes into Lightbox.ShowLightbox() like this: *====================================================================* tlVisibility - show or hide (T/F)* grab a screen dump with controls*====================================================================Lparameters tlVisibility Local loControl m.loControl = This.oControl If m.tlVisibility Local loCaptureBmp As xfcBitmap Local lnTitleHeight, lnLeftBorder, lnTopBorder, lcImage, loImage lnTitleHeight = Iif(m.loControl.TitleBar = 1,Sysmetric(9),0) lnLeftBorder = Iif(m.loControl.BorderStyle < 2,0,Sysmetric(3)) lnTopBorder = Iif(m.loControl.BorderStyle < 2,0,Sysmetric(4)) With _Screen.System.Drawing If Upper(m.loControl.Name) == Upper("Screen") loCaptureBmp = .Bitmap.FromScreen(m.loControl.HWnd) Else loCaptureBmp = .Bitmap.FromScreen(m.loControl.HWnd,; lnLeftBorder,; lnTopBorder+lnTitleHeight,; m.loControl.Width ,; m.loControl.Height) EndIf Endwith * save it to a property This.CaptureBmp = loCaptureBmp m.loControl.SetAll("Visible",.F.) This.Draw() This.Visible = .T. Else This.CaptureBmp = .Null. m.loControl.SetAll("Visible",.T.) This.Visible = .F. Endif {loadposition content_adsense} Are we done? Almost... Although, Bernard says it clearly in his article: "Just drop the class on a form and call it as shown." It did not come clear to my mind in the first place with _Screen, but, yeah, he is right. Dropping the class on a form provides a permanent link between those two classes, it creates a valid This.Parent object reference. Bearing in mind that the lightbox class can not be "dropped" on the _Screen, we have to create the same type of binding during runtime execution like so: *====================================================================* Create global lightbox component*==================================================================== Local llOk, loException As Exception m.llOk = .F. m.loException = .Null. If Not Vartype(_Screen.Lightbox) == "O" Try _Screen.AddObject("Lightbox", "bbGdiLightbox") Catch To m.loException Assert .F. Message m.loException.Message EndTry EndIf m.llOk = (Vartype(_Screen.Lightbox) == "O")Return m.llOk Through runtime instantiation we create a valid binding to This.Parent in the lightbox object and the code works as expected with _Screen. Ease your life: Use properties instead of constants Having a closer look at the BeforeDraw() method might wet your appetite to simplify the code a little bit. Looking at the sample screenshots in Bernard's article you see several forms in different colors. This got me to modify the code like so: *====================================================================* Apply the actual lightbox effect on the captured bitmap.*====================================================================If Vartype(This.CaptureBmp) == T_OBJECT Local loGfx As xfcGraphics loGfx = This.oGfx With _Screen.System.Drawing loGfx.DrawImage(This.CaptureBmp,This.Rectangle,This.Rectangle,.GraphicsUnit.Pixel) * change the colours as needed here * possible colours are (220,128,0,0),(220,0,0,128) etc. loBrush = .SolidBrush.New(.Color.FromArgb( ; This.Opacity, .Color.FromRGB(This.BorderColor))) loGfx.FillRectangle(loBrush,This.Rectangle) EndwithEndif Create an additional property Opacity to specify the grade of translucency you would like to have without the need to change the code in each instance of the class. This way you only need to change the values of Opacity and BorderColor to tweak the appearance of your lightbox. This could be quite helpful to signalize different levels of importance (ie. green, yellow, orange, red, etc...) of notifications to the users of the application. Final thoughts Using the lightbox concept in combination with _Screen instead of forms is possible. Already Jim Wiggins comments in Bernard's article to loop through the _Screen.Forms collection in order to cascade the lightbox visibility to all active forms. Good idea. But honestly, I believe that instead of looping all forms one could use _Screen.SetAll("ShowLightbox", .T./.F., "Form") with Form.ShowLightbox_Access method to gain more speed. The modifications described above might provide even more features to your applications while consuming less resources and performance. Additionally, the restrictions to capture only forms does not exist anymore. Using _Screen you are able to capture and cover anything. The captured area of _Screen does not include any toolbars, docked windows, or menus. Therefore, it is advised to take this concept on a higher level and to combine it with additional classes that handle the state of toolbars, docked windows and menus. Which I did for the customer's project.

    Read the article

  • Car animations in Frogger on Javascript

    - by Mijoro Nicolas Rasoanaivo
    I have to finish a Frogger game in Javascript for my engineering school degree, but I don't know how to animate the cars. Right now I tried to manipulate the CSS, the DOM, I wrote a script with a setTimeout(), but none of them works.Can I have some help please? Here's my code and my CSS: <html> <head> <title>Image d&eacute;filante</title> <link rel="stylesheet" type="text/css" href="map_style.css"/> </head> <body onload="start()"> <canvas id="jeu" width="800" height="450"> </canvas> <img id="voiture" class="voiture" src="car.png" onload="startTimerCar()"> <img id="voiture2" class="voiture" src="car.png" onload="startTimerCar()"> <img id="voiture3" class="voiture" src="car.png" onload="startTimerCar()"> <img id="bigrig" class="bigrig" src="bigrig.png" onload="startTimerBigrig()"> <img id="bigrig2" class="bigrig" src="bigrig.png" onload="startTimerBigrig()"> <img id="bigrig3" class="bigrig" src="bigrig.png" onload="startTimerBigrig()"> <img id="hotrod" src="hotrod.png" onload="startTimerHotrod()"> <img id="hotrod2" src="hotrod.png" onload="startTimerHotrod()"> <img id="turtle" src="turtles_diving.png" onload="startTimerTurtle()"> <img id="turtle2" src="turtles_diving.png" onload="startTimerTurtle()"> <img id="turtle3" src="turtles_diving.png" onload="startTimerTurtle()"> <img id="small" src="log_small.png" onload="startTimerSmall()"> <img id="small2" src="log_small.png" onload="startTimerSmall()"> <img id="small3" src="log_small.png" onload="startTimerSmall()"> <img id="small4" src="log_small.png" onload="startTimerSmall()"> <img id="med" src="log_medium.png" onload="startTimerMedium()"> <img id="med2" src="log_medium.png" onload="startTimerMedium()"> <img id="med3" src="log_medium.png" onload="startTimerMedium()"> <script type="text/javascript"> var X = 1; var timer; function start(){ setInterval(init,10); document.onkeydown = move; var canvas = document.getElementById('jeu'); var context = canvas.getContext('2d'); var frog = document.getElementById('frog'); var posX_frog = 415; var posY_frog = 400; var voiture = [document.getElementById('voiture'),document.getElementById('voiture2'),document.getElementById('voiture3')]; var bigrig = [document.getElementById('bigrig'),document.getElementById('bigrig2'),document.getElementById('bigrig3')]; var hotrod = [document.getElementById('hotrod'),document.getElementById('hotrod2')]; var turtle = [document.getElementById('turtle'),document.getElementById('turtle2'),document.getElementById('turtle3')]; var small = [document.getElementById('small'),document.getElementById('small2'),document.getElementById('small3'),document.getElementById('small4')]; var med = [document.getElementById('med'),document.getElementById('med2'),document.getElementById('med3')]; function init() { context.fillStyle = "#AEEE00"; context.fillRect(0,0,800,50); context.fillRect(0,200,800,50); context.fillRect(0,400,800,50); context.fillStyle = "#046380"; context.fillRect(0,50,800,150); context.fillStyle = "#000000"; context.fillRect(0,250,800,150); var img= new Image(); img.src="./frog.png"; context.drawImage(img,posX_frog, posY_frog, 46, 38); } function move(event){ if (event.keyCode == 39){ if( posX_frog < 716 ){ posX_frog += 50; } } if(event.keyCode == 37){ if( posX_frog >25 ){ posX_frog -= 50; } } if (event.keyCode == 38){ if( posY_frog > 10 ){ posY_frog -= 50; } } if(event.keyCode == 40){ if( posY_frog <400 ){ posY_frog += 50; } } } } </script> </body> And my map_css: #jeu{ z-index:10; width: 800px; height: 450px; border: 2px black solid; overflow: hidden; position: relative; transition:width 2s; -moz-transition:width 2s; /* Firefox 4 */ -webkit-transition:width 2s; /* Safari and Chrome */ } #voiture{ z-index: 100; position: absolute; top: 315px; left: 48px; transition-timing-function: linear; -webkit-transition-timing-function: linear; -moz-transition-timing-function: linear; } #voiture2{ z-index: 100; position: absolute; top: 315px; left: 144px; } #voiture3{ z-index: 100; position: absolute; top: 315px; left: 240px; } #bigrig{ z-index: 100; position: absolute; top: 365px; left: 200px; } #bigrig2{ z-index: 100; position: absolute; top: 365px; left: 400px; } #bigrig3{ z-index: 100; position: absolute; top: 365px; left: 600px; } #hotrod{ z-index: 100; position: absolute; top: 265px; left: 200px; } #hotrod2{ z-index: 100; position: absolute; top: 265px; left: 500px; } #hotrod3{ z-index: 100; position: absolute; top: 265px; left: 750px; } #turtle{ z-index: 100; position: absolute; top: 175px; left: 50px; } #turtle2{ z-index: 100; position: absolute; top: 175px; left: 450px; } #turtle3{ z-index: 100; position: absolute; top: 175px; left: 250px; } #small{ z-index: 100; position: absolute; top: 125px; left: 20px; } #small2{ z-index: 100; position: absolute; top: 125px; left: 220px; } #small3{ z-index: 100; position: absolute; top: 125px; left: 420px; } #small4{ z-index: 100; position: absolute; top: 125px; left: 620px; } #med{ z-index: 100; position: absolute; top: 75px; left: 120px; } #med2{ z-index: 100; position: absolute; top: 75px; left: 320px; } #med3{ z-index: 100; position: absolute; top: 75px; left: 520px; } I had to say that I'm in the obligation to code in HTML5, CSS3, and Javascript but not jQuery, who is way more easier, I already created games in jQuery... It takes me too much time and too much code lines right here.

    Read the article

  • Loading PNGs into OpenGL performance issues - Java & JOGL much slower than C# & Tao.OpenGL

    - by Edward Cresswell
    I am noticing a large performance difference between Java & JOGL and C# & Tao.OpenGL when both loading PNGs from storage into memory, and when loading that BufferedImage (java) or Bitmap (C# - both are PNGs on hard drive) 'into' OpenGL. This difference is quite large, so I assumed I was doing something wrong, however after quite a lot of searching and trying different loading techniques I've been unable to reduce this difference. With Java I get an image loaded in 248ms and loaded into OpenGL in 728ms The same on C# takes 54ms to load the image, and 34ms to load/create texture. The image in question above is a PNG containing transparency, sized 7200x255, used for a 2D animated sprite. I realise the size is really quite ridiculous and am considering cutting up the sprite, however the large difference is still there (and confusing). On the Java side the code looks like this: BufferedImage image = ImageIO.read(new File(fileName)); texture = TextureIO.newTexture(image, false); texture.setTexParameteri(GL.GL_TEXTURE_MIN_FILTER, GL.GL_LINEAR); texture.setTexParameteri(GL.GL_TEXTURE_MAG_FILTER, GL.GL_LINEAR); The C# code uses: Bitmap t = new Bitmap(fileName); t.RotateFlip(RotateFlipType.RotateNoneFlipY); Rectangle r = new Rectangle(0, 0, t.Width, t.Height); BitmapData bd = t.LockBits(r, ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb); Gl.glBindTexture(Gl.GL_TEXTURE_2D, tID); Gl.glTexImage2D(Gl.GL_TEXTURE_2D, 0, Gl.GL_RGBA, t.Width, t.Height, 0, Gl.GL_BGRA, Gl.GL_UNSIGNED_BYTE, bd.Scan0); Gl.glTexParameteri(Gl.GL_TEXTURE_2D, Gl.GL_TEXTURE_MIN_FILTER, Gl.GL_LINEAR); Gl.glTexParameteri(Gl.GL_TEXTURE_2D, Gl.GL_TEXTURE_MAG_FILTER, Gl.GL_LINEAR); t.UnlockBits(bd); t.Dispose(); After quite a lot of testing I can only come to the conclusion that Java/JOGL is just slower here - PNG reading might not be as quick, or that I'm still doing something wrong. Thanks. Edit2: I have found that creating a new BufferedImage with format TYPE_INT_ARGB_PRE decreases OpenGL texture load time by almost half - this includes having to create the new BufferedImage, getting the Graphics2D from it and then rendering the previously loaded image to it. Edit3: Benchmark results for 5 variations. I wrote a small benchmarking tool, the following results come from loading a set of 33 pngs, most are very wide, 5 times. testStart: ImageIO.read(file) -> TextureIO.newTexture(image) result: avg = 10250ms, total = 51251 testStart: ImageIO.read(bis) -> TextureIO.newTexture(image) result: avg = 10029ms, total = 50147 testStart: ImageIO.read(file) -> TextureIO.newTexture(argbImage) result: avg = 5343ms, total = 26717 testStart: ImageIO.read(bis) -> TextureIO.newTexture(argbImage) result: avg = 5534ms, total = 27673 testStart: TextureIO.newTexture(file) result: avg = 10395ms, total = 51979 ImageIO.read(bis) refers to the technique described in James Branigan's answer below. argbImage refers to the technique described in my previous edit: img = ImageIO.read(file); argbImg = new BufferedImage(img.getWidth(), img.getHeight(), TYPE_INT_ARGB_PRE); g = argbImg.createGraphics(); g.drawImage(img, 0, 0, null); texture = TextureIO.newTexture(argbImg, false); Any more methods of loading (either images from file, or images to OpenGL) would be appreciated, I will update these benchmarks.

    Read the article

  • asp.net image aspect ratio help

    - by StealthRT
    Hey all, i am in need of some help with keeping an image aspect ratio in check. This is the aspx code that i have to resize and upload an image the user selects. <%@ Page Trace="False" Language="vb" aspcompat="false" debug="true" validateRequest="false"%> <%@ Import Namespace=System.Drawing %> <%@ Import Namespace=System.Drawing.Imaging %> <%@ Import Namespace=System %> <%@ Import Namespace=System.Web %> <SCRIPT LANGUAGE="VBScript" runat="server"> const Lx = 500 ' max width for thumbnails const Ly = 60 ' max height for thumbnails const upload_dir = "/uptest/" ' directory to upload file const upload_original = "sample" ' filename to save original as (suffix added by script) const upload_thumb = "thumb" ' filename to save thumbnail as (suffix added by script) const upload_max_size = 512 ' max size of the upload (KB) note: this doesn't override any server upload limits dim fileExt ' used to store the file extension (saves finding it mulitple times) dim newWidth, newHeight as integer ' new width/height for the thumbnail dim l2 ' temp variable used when calculating new size dim fileFld as HTTPPostedFile ' used to grab the file upload from the form Dim originalimg As System.Drawing.Image ' used to hold the original image dim msg ' display results dim upload_ok as boolean ' did the upload work ? </script> <% randomize() ' used to help the cache-busting on the preview images upload_ok = false if lcase(Request.ServerVariables("REQUEST_METHOD"))="post" then fileFld = request.files(0) ' get the first file uploaded from the form (note:- you can use this to itterate through more than one image) if fileFld.ContentLength > upload_max_size * 1024 then msg = "Sorry, the image must be less than " & upload_max_size & "Kb" else try originalImg = System.Drawing.Image.FromStream(fileFld.InputStream) ' work out the width/height for the thumbnail. Preserve aspect ratio and honour max width/height ' Note: if the original is smaller than the thumbnail size it will be scaled up If (originalImg.Width/Lx) > (originalImg.Width/Ly) Then L2 = originalImg.Width newWidth = Lx newHeight = originalImg.Height * (Lx / L2) if newHeight > Ly then newWidth = newWidth * (Ly / newHeight) newHeight = Ly end if Else L2 = originalImg.Height newHeight = Ly newWidth = originalImg.Width * (Ly / L2) if newWidth > Lx then newHeight = newHeight * (Lx / newWidth) newWidth = Lx end if End If Dim thumb As New Bitmap(newWidth, newHeight) 'Create a graphics object Dim gr_dest As Graphics = Graphics.FromImage(thumb) ' just in case it's a transparent GIF force the bg to white dim sb = new SolidBrush(System.Drawing.Color.White) gr_dest.FillRectangle(sb, 0, 0, thumb.Width, thumb.Height) 'Re-draw the image to the specified height and width gr_dest.DrawImage(originalImg, 0, 0, thumb.Width, thumb.Height) try fileExt = System.IO.Path.GetExtension(fileFld.FileName).ToLower() originalImg.save(Server.MapPath(upload_dir & upload_original & fileExt), originalImg.rawformat) thumb.save(Server.MapPath(upload_dir & upload_thumb & fileExt), originalImg.rawformat) msg = "Uploaded " & fileFld.FileName & " to " & Server.MapPath(upload_dir & upload_original & fileExt) upload_ok = true catch msg = "Sorry, there was a problem saving the image." end try ' Housekeeping for the generated thumbnail if not thumb is nothing then thumb.Dispose() thumb = nothing end if catch msg = "Sorry, that was not an image we could process." end try end if ' House Keeping ! if not originalImg is nothing then originalImg.Dispose() originalImg = nothing end if end if %> What i am looking for is a way to just have it go by the height of what i set it: const Ly = 60 ' max height for thumbnails And have the code for the width just be whatever. So if i had an image... say 600 x 120 (w h) and i used photoshop to change just the height, it would keep it in ratio and have it 300 x 60 (w x h). Thats what i am looking to do with this code here. However, i can not think of a way to do this (or to just leave a wildcard for the width setting. Any help would be great :o) David

    Read the article

  • [Java] Cannot draw pixels

    - by Wilhelm
    Hello everyone. I want to print each digit of pi number as a colored pixel, so, I get na input, with the pi number, then parse it into a list, each node containing a digit (I know, I'll use an array later), but I never get this painted to screen... Can someone help me to see where I'm wrong? package edu.pi.view; import java.awt.Graphics; import java.awt.Image; import java.awt.image.MemoryImageSource; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.util.ArrayList; import java.util.List; import javax.swing.JFrame; import javax.swing.JPanel; public class Main extends JPanel { private static final long serialVersionUID = 6416932054834995251L; private static int pixels[]; private static List<Integer> pi; public static void readFile(String name) { File file = new File(name); BufferedReader reader = null; pi = new ArrayList<Integer>(); char[] digits; try { reader = new BufferedReader(new FileReader(file)); String text = null; while((text = reader.readLine()) != null) { digits = text.toCharArray(); for(char el : digits) if(el != ' ') pi.add(Character.getNumericValue(el)); } } catch (Exception e) { e.printStackTrace(); } } public void paint(Graphics gg) { readFile("c:\\pi.txt"); int h = 5; int w = 2; int color = 0xffffff; int digit; int i = 0; pixels = new int[w * h]; for (int y = 0; y < h; y++) { for (int x = 0; x < h; x++) { digit = pi.get(i); if(digit == 0) color = 0x000000; else if(digit == 1) color = 0x787878; else if(digit == 2) color = 0x008B00; else if(digit == 3) color = 0x00008B; else if(digit == 4) color = 0x008B8B; else if(digit == 5) color = 0x008B00; else if(digit == 6) color = 0xCDCD00; else if(digit == 7) color = 0xFF4500; else if(digit == 8) color = 0x8B0000; else if(digit == 9) color = 0xFF0000; pixels[i] = color; i++; } } Image art = createImage(new MemoryImageSource(w, h, pixels, 0, w)); gg.drawImage(art, 0, 0, this); } public static void main(String[] args) { JFrame frame = new JFrame(); frame.getContentPane().add(new Main()); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(300,300); frame.setVisible(true); } }

    Read the article

  • JPanel paint method is not being called, why?

    - by swift
    When i run this code the paintComponent method is not being called It may be very simple error but i dont know why this, plz. package test; import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Point; import java.awt.image.BufferedImage; import javax.swing.BorderFactory; import javax.swing.JPanel; class Userboard extends JPanel { static BufferedImage image; String shape; Point start; Point end; Point mp; String selected; int ex,ey;//eraser int w,h; public Userboard() { setOpaque(false); System.out.println("paper"); setBackground(Color.white); setBorder(BorderFactory.createLineBorder(Color.black)); } public void paintComponent(Graphics g) { System.out.println("userboard-paint"); try { //g.drawImage(image, 0, 0, this); Graphics2D g2 = (Graphics2D)g; g2.setPaint(Color.black); if(start!=null && end!=null) { if(selected==("elipse")) { System.out.println("userboard-elipse"); g2.drawOval(start.x, start.y,(end.x-start.x),(end.y-start.y)); System.out.println("userboard-elipse drawn"); } else if(selected==("rect")) g2.drawRect(start.x, start.y, (end.x-start.x),(end.y-start.y)); else if(selected==("line")) g2.drawLine(start.x,start.y,end.x,end.y); } } catch(Exception e) {} } //Function to draw the shape on image public void draw() { System.out.println("Userboard-draw"); System.out.println(selected); System.out.println(start); System.out.println(end); Graphics2D g2 = image.createGraphics(); g2.setPaint(Color.black); if(start!=null && end!=null) { if(selected=="line") g2.drawLine(start.x, start.y, end.x, end.y); else if(selected=="elipse") { System.out.println("userboard-elipse"); g2.drawOval(start.x, start.y, (end.x-start.x),(end.y-start.y)); System.out.println("userboard-elipse drawn"); } else if(selected=="rect") g2.drawRect(start.x, start.y, (end.x-start.x),(end.y-start.y)); } start=null; repaint(); g2.dispose(); } //To add the point to the board which is broadcasted by the server public void addPoint(Point ps,String varname,String shape,String event) { try { if(end==null) end = new Point(); if(start==null) start = new Point(); if(shape.equals("elipse")) this.selected="elipse"; else if(shape.equals("line")) this.selected="line"; else if(shape.equals("rect")) this.selected="rect"; else if(shape.equals("erase")) erase(); if(end!=null && start!=null) { if(varname.equals("end")) end=ps; else if(varname.equals("mp")) mp=ps; else if(varname.equals("start")) start=ps; if(event.equals("drag")) repaint(); else if(event.equals("release")) draw(); } repaint(); } catch(Exception e) { e.printStackTrace(); } } //Function which provides the erase functionality public void erase() { Graphics2D pic=(Graphics2D) image.getGraphics(); pic.setPaint(Color.white); if(start!=null) pic.fillRect(start.x, start.y, 10, 10); } //To set the size of the image public void setWidth(int x,int y) { System.out.println("("+x+","+y+")"); w=x; h=y; image = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB); } //Function to add buttons into the panel, calling this function returns a panel }

    Read the article

  • DoubleBuffering in Java

    - by DDP
    Hello there, I'm having some trouble implementing DoubleBuffer into my program. Before you faint from the wall of text, you should know that a lot of it is there just in case you need to know. The actual place where I think I'm having problems is in one method. I've recently looked up a tutorial on the gpwiki about double buffering, and decided to try and implement the code they had into the code I have that I'm trying to implement doublebuffer in. I get the following error: "java.lang.IllegalStateException: Component must have a valid peer". I don't know if it makes any difference if you know it or not, but the following is the code with the main method. This is just a Frame that displays the ChronosDisplay class inside it. I omitted irrelevant code with "..." public class CDM extends JFrame { public CDM(String str) { super("CD:M - "+str); try { ... ChronosDisplay theGame = new ChronosDisplay(str); ((Component)theGame).setFocusable(true); add(theGame); } catch(Exception e) { System.out.println("CDM ERROR: " +e); } } public static void main( String args[] ) { CDM run = new CDM("DP_Mini"); } } Here is the code where I think the problem resides (I think the problem is in the paint() method). This class is displayed in the CDM class public class ChronosDisplay extends Canvas implements Runnable { String mapName; public ChronosDisplay (String str) { mapName = str; new Thread(this).start(); setVisible(true); createBufferStrategy(2); } public void paint( Graphics window ) { BufferStrategy b = getBufferStrategy(); Graphics g = null; window.setColor(Color.white); try { g = b.getDrawGraphics(); paintMap(g); paintUnits(g); paintBullets(g); } finally { g.dispose(); } b.show(); Toolkit.getDefaultToolkit().sync(); } public void paintMap( Graphics window ) { TowerMap m = new TowerMap(); try { m = new TowerMap(mapName); for(int x=0; x<m.getRows()*50; x+=50) { for(int y = 0; y<m.getCols()*50; y+=50) { int tileType = m.getLocation(x/50,y/50); Image img; if(tileType == 0) { Tile0 t = new Tile0(x,y); t.draw(window); } ...// More similar if statements for other integers } catch(Exception e) ... } ...// Additional methods not shown here public void run() { try { while(true) { Thread.currentThread().sleep(20); repaint(); } } catch(Exception e) ... } } If you're curious (I doubt it matters), the draw() method in the Tile0 class is: public void draw( Graphics window ) { window.drawImage(img,getX(),getY(),50,50,null); } Any pointers, tips, or solutions are greatly appreciated. Thanks for your time! :D

    Read the article

  • zoom a JPanel and all of its components

    - by user253530
    I have a big JPanel which holds many TileMapping objects (TileMapping extends JPanel). I want to zoom the big JPanel and all of its components to be scaled aswell. A TileMapping has an image which of course has to be zoomed as well. here is my TileMapping class public class TileMapping extends JPanel { private double zoom = 1.0; private Mapping mapping; private int height; private int width; private int xCoord; private int yCoord; TileMapping(Mapping m, int w, int h, int x, int y) { super(); mapping = m; height = h; width = w; this.xCoord = x; this.yCoord = y; this.setPreferredSize(new Dimension(w, h)); } public int getXcoord() { return xCoord; } public int getYcoord() { return yCoord; } public Mapping getMapping() { return mapping; } public void setMapping(Mapping m) { mapping = m; } public void originalSize() { zoom = 1; } public void zoomIn() { zoom += 0.2; } public void zoomOut() { zoom -= 0.2; } @Override public void paintComponent(Graphics g) { Graphics2D g2d = (Graphics2D) g; if (mapping.getImage() != null) { BufferedImage bg = mapping.getImage(); g2d.scale(zoom, zoom); g2d.drawImage(bg, 0, 0, width, height, this); } else { g2d.scale(zoom, zoom); this.setBackground(Color.white); } } } I need to know how i should continue this on the main JPanel which is populated using this code: This is part of a MapWindow class. if you carefully read the code you will understand what i'm talking about. Basically this is a Tile MapEditor and I am simulating a Tile as a JPanel which holds the mapping object (mapping is a binding between an ASCII character and an image) you place. private void populateMapPanel(Map map) { GridBagConstraints c = new GridBagConstraints(); mapPanel.setLayout(new GridBagLayout()); for (int i = 0; i < map.getMapGrid().getRows(); i++) { for (int j = 0; j < map.getMapGrid().getColumns(); j++) { tile = new TileMapping(map.getMapItem(i, j), cellSize, cellSize, i, j); tile.setBorder(new LineBorder(Color.black)); tile.addMouseListener(this); tile.addMouseMotionListener(this); c.gridx = i; c.gridy = j; mapPanel.add(tile, c); } } mapPanel.validate(); mapPanel.repaint(); } I need to know how to do the following: 1. When the user presses Zoom In the mapPanel should zoom in and also all the images in the smaller panels. 2. when the user click and drag over the TileMappings an image should be painted on them and this image should get scaled of course if the mapPanel is zoomed. Pseudo code, ideas, hints, java code ...anything would be helpful. Thank you

    Read the article

  • How to make a character jump, both on objects and just normal jump.

    - by haxerflaxer
    Hi, I'm kind of a beginner when it comes to java programming, and I have a project in school where I'm going to create a game much like Icy Tower. And my question is, how am I going to write to make the character stand on the ground and be able to jump up on objects? Here's my code so far: Part one package Sprites; import java.awt.Image; import java.awt.event.KeyEvent; import javax.swing.ImageIcon; public class jumper { private String jump = "oka.png"; private int dx; private int dy; private int x; private int y; private Image image; public jumper() { ImageIcon ii = new ImageIcon(this.getClass().getResource(jump)); image = ii.getImage(); x = 50; y = 100; } public void move() { x += dx; y += dy; } public int getX() { return x; } public int getY() { return y; } public Image getImage() { return image; } public void keyPressed(KeyEvent e) { int key = e.getKeyCode(); if (key == KeyEvent.VK_LEFT) { dx = -5; ImageIcon ii = new ImageIcon(this.getClass().getResource("oki.png")); image = ii.getImage(); } if (key == KeyEvent.VK_RIGHT){ dx = 5; ImageIcon ii = new ImageIcon(this.getClass().getResource("oka.png")); image = ii.getImage(); } if (key == KeyEvent.VK_SPACE) { dy = -5; } if (key == KeyEvent.VK_DOWN) { dy = 5; } } public void keyReleased(KeyEvent e) { int key = e.getKeyCode(); if (key == KeyEvent.VK_LEFT) { dx = 0; } if (key == KeyEvent.VK_RIGHT){ dx = 0; } if (key == KeyEvent.VK_SPACE) { dy = 0; } if (key == KeyEvent.VK_DOWN) { dy = 0; } } } Part two package Sprites; import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import javax.swing.JPanel; import javax.swing.Timer; public class board extends JPanel implements ActionListener { private Timer klocka; private jumper jumper; public board() { addKeyListener(new TAdapter()); setFocusable(true); setBackground(Color.WHITE); setDoubleBuffered(true); jumper = new jumper(); klocka = new Timer(5, this); klocka.start(); } public void paint(Graphics g) { super.paint(g); Graphics2D g2d = (Graphics2D)g; g2d.drawImage(jumper.getImage(), jumper.getX(), jumper.getY(), this); Toolkit.getDefaultToolkit().sync(); g.dispose(); } public void actionPerformed(ActionEvent e) { jumper.move(); repaint(); } private class TAdapter extends KeyAdapter { public void keyReleased(KeyEvent e) { jumper.keyReleased(e); } public void keyPressed(KeyEvent e) { jumper.keyPressed(e); } } } Part three package Sprites; import javax.swing.JFrame; public class RType extends JFrame { public RType() { add(new board()); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setSize(800, 600); setLocationRelativeTo(null); setTitle("R - type"); setResizable(false); setVisible(true); } public static void main(String[] args) { new RType(); } } I really appreciate all the help I can get!

    Read the article

  • How do you make a character jump, both on objects and just normal jump?

    - by haxerflaxer
    Hi, I'm kind of a beginner when it comes to java programming, and I have a project in school where I'm going to create a game much like Icy Tower. And my question is, how am I going to write to make the character stand on the ground and be able to jump up on objects? Here's my code so far: Part one package Sprites; import java.awt.Image; import java.awt.event.KeyEvent; import javax.swing.ImageIcon; public class jumper { private String jump = "oka.png"; private int dx; private int dy; private int x; private int y; private Image image; public jumper() { ImageIcon ii = new ImageIcon(this.getClass().getResource(jump)); image = ii.getImage(); x = 50; y = 100; } public void move() { x += dx; y += dy; } public int getX() { return x; } public int getY() { return y; } public Image getImage() { return image; } public void keyPressed(KeyEvent e) { int key = e.getKeyCode(); if (key == KeyEvent.VK_LEFT) { dx = -5; ImageIcon ii = new ImageIcon(this.getClass().getResource("oki.png")); image = ii.getImage(); } if (key == KeyEvent.VK_RIGHT){ dx = 5; ImageIcon ii = new ImageIcon(this.getClass().getResource("oka.png")); image = ii.getImage(); } if (key == KeyEvent.VK_SPACE) { dy = -5; } if (key == KeyEvent.VK_DOWN) { dy = 5; } } public void keyReleased(KeyEvent e) { int key = e.getKeyCode(); if (key == KeyEvent.VK_LEFT) { dx = 0; } if (key == KeyEvent.VK_RIGHT){ dx = 0; } if (key == KeyEvent.VK_SPACE) { dy = 0; } if (key == KeyEvent.VK_DOWN) { dy = 0; } } } Part two package Sprites; import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import javax.swing.JPanel; import javax.swing.Timer; public class board extends JPanel implements ActionListener { private Timer klocka; private jumper jumper; public board() { addKeyListener(new TAdapter()); setFocusable(true); setBackground(Color.WHITE); setDoubleBuffered(true); jumper = new jumper(); klocka = new Timer(5, this); klocka.start(); } public void paint(Graphics g) { super.paint(g); Graphics2D g2d = (Graphics2D)g; g2d.drawImage(jumper.getImage(), jumper.getX(), jumper.getY(), this); Toolkit.getDefaultToolkit().sync(); g.dispose(); } public void actionPerformed(ActionEvent e) { jumper.move(); repaint(); } private class TAdapter extends KeyAdapter { public void keyReleased(KeyEvent e) { jumper.keyReleased(e); } public void keyPressed(KeyEvent e) { jumper.keyPressed(e); } } } Part three package Sprites; import javax.swing.JFrame; public class RType extends JFrame { public RType() { add(new board()); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setSize(800, 600); setLocationRelativeTo(null); setTitle("R - type"); setResizable(false); setVisible(true); } public static void main(String[] args) { new RType(); } } I really appreciate all the help I can get!

    Read the article

  • Using my custom colormap in Java for images

    - by John
    Hi everyone! I've got a question concering a colormapping via index. I tried this code found on http://www.podgoretsky.pri.ee/ftp/Docs/Java/Tricks%20of%20the%20Java%20Programming%20Gurus/ch12.htm // Gradient.java // Imports import java.applet.Applet; import java.awt.; import java.awt.image.; public class Gradient extends Applet { final int colors = 32; final int width = 200; final int height = 200; Image img; public void init() { // Create the color map byte[] rbmap = new byte[colors]; byte[] gmap = new byte[colors]; for (int i = 0; i < colors; i++) gmap[i] = (byte)((i * 255) / (colors - 1)); // Create the color model int bits = (int)Math.ceil(Math.log(colors) / Math.log(2)); IndexColorModel model = new IndexColorModel(bits, colors, rbmap, gmap, rbmap); // Create the pixels int pixels[] = new int[width * height]; int index = 0; for (int y = 0; y < height; y++) for (int x = 0; x < width; x++) pixels[index++] = (x * colors) / width; // Create the image img = createImage(new MemoryImageSource(width, height, model, pixels, 0, width)); } public void paint(Graphics g) { g.drawImage(img, 0, 0, this); } } It worked great but I tried to load a custom image jpeg mapped on my own colormap but it didnt work right. I saw only a bunch of green and blue pixels drawn on a white background. My custom color map method here: public void inintByteArrays() { double[][] c = // basic color map { { 0.0000, 0.0000, 0.5625 }, { 0.0000, 0.0000, 0.6250 }, { 0.0000, 0.0000, 0.6875 }, { 0.0000, 0.0000, 0.6875 }, { 0.0000, 0.0000, 0.7500 }, { 0.0000, 0.0000, 0.8125 }, { 0.0000, 0.0000, 0.8750 }, { 0.0000, 0.0000, 0.9375 }, { 0.0000, 0.0000, 1.0000 }, { 0.0000, 0.0625, 1.0000 }, { 0.0000, 0.1250, 1.0000 }, { 0.0000, 0.1875, 1.0000 }, { 0.0000, 0.2500, 1.0000 }, { 0.0000, 0.3125, 1.0000 }, { 0.0000, 0.3750, 1.0000 }, { 0.0000, 0.4375, 1.0000 }, { 0.0000, 0.5000, 1.0000 }, { 0.0000, 0.5625, 1.0000 }, { 0.0000, 0.6250, 1.0000 }, { 0.0000, 0.6875, 1.0000 }, { 0.0000, 0.7500, 1.0000 }, { 0.0000, 0.8125, 1.0000 }, { 0.0000, 0.8750, 1.0000 }, { 0.0000, 0.9375, 1.0000 }, { 0.0000, 1.0000, 1.0000 }, { 0.0625, 1.0000, 0.9375 }, { 0.1250, 1.0000, 0.8750 }, { 0.1875, 1.0000, 0.8125 }, { 0.2500, 1.0000, 0.7500 }, { 0.3125, 1.0000, 0.6875 }, { 0.3750, 1.0000, 0.6250 }, { 0.4375, 1.0000, 0.5625 }, { 0.5000, 1.0000, 0.5000 }, { 0.5625, 1.0000, 0.4375 }, { 0.6250, 1.0000, 0.3750 }, { 0.6875, 1.0000, 0.3125 }, { 0.7500, 1.0000, 0.2500 }, { 0.8125, 1.0000, 0.1875 }, { 0.8750, 1.0000, 0.1250 }, { 0.9375, 1.0000, 0.0625 }, { 1.0000, 1.0000, 0.0000 }, { 1.0000, 0.9375, 0.0000 }, { 1.0000, 0.8750, 0.0000 }, { 1.0000, 0.8125, 0.0000 }, { 1.0000, 0.7500, 0.0000 }, { 1.0000, 0.6875, 0.0000 }, { 1.0000, 0.6250, 0.0000 }, { 1.0000, 0.5625, 0.0000 }, { 1.0000, 0.5000, 0.0000 }, { 1.0000, 0.4375, 0.0000 }, { 1.0000, 0.3750, 0.0000 }, { 1.0000, 0.3125, 0.0000 }, { 1.0000, 0.2500, 0.0000 }, { 1.0000, 0.1875, 0.0000 }, { 1.0000, 0.1250, 0.0000 }, { 1.0000, 0.0625, 0.0000 }, { 1.0000, 0.0000, 0.0000 }, { 0.9375, 0.0000, 0.0000 }, { 0.8750, 0.0000, 0.0000 }, { 0.8125, 0.0000, 0.0000 }, { 0.7500, 0.0000, 0.0000 }, { 0.6875, 0.0000, 0.0000 }, { 0.6250, 0.0000, 0.0000 }, { 0.5625, 0.0000, 0.0000 }, { 0.5000, 0.0000, 0.0000 } }; for (int i = 0; i < c.length; i++) { for (int j = 0; j < c[i].length; j++) { if (j == 0) r[i] = (byte) ((byte) c[i][j]*255); if (j == 1) g[i] = (byte) ((byte) c[i][j]*255); if (j == 2) b[i] = (byte) ((byte) c[i][j]*255); } } My question is how I can use my colormap for any image I want to load and map in the right way. Thank you very much! Greetings, protein1.

    Read the article

  • How do I set an event off when player is on certain tile?

    - by Tom Burman
    Here is the code I use to create and print my map to the canvas: var board = []; function loadMap(map) { if (map == 1) { return [ [2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2], [2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2], [2,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2], [2,0,0,3,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,3,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2], [2,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,3,0,3,3,3,0,0,0,0,0,0,0,0,0,0,0,0,0,2], [2,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,3,3,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,3,3,3,3,0,0,0,0,0,0,0,0,0,2], [2,0,0,0,0,3,3,0,0,0,0,0,0,0,0,0,3,3,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,3,0,0,0,0,0,3,0,0,2], [2,0,0,0,0,0,0,3,0,0,0,0,0,0,0,3,3,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,2], [2,0,0,0,0,0,0,3,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,2], [2,0,0,0,0,0,0,0,3,3,0,0,0,0,3,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,2], [2,0,0,0,0,0,0,0,0,0,3,3,0,0,3,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,3,0,0,2], [2,0,0,0,0,0,0,0,0,0,0,3,0,3,0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,2], [2,0,0,0,0,0,0,0,0,0,0,0,3,3,3,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2], [2,0,0,0,0,0,0,0,0,0,0,0,0,0,3,3,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,2], [2,0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,3,3,3,3,0,0,0,0,3,3,0,0,0,0,0,0,0,0,0,2], [2,0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,3,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,2], [2,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,2], [2,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,3,3,0,0,0,0,0,0,0,2], [2,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,2], [2,0,0,0,0,0,0,0,0,3,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,3,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,2], [2,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,2], [2,0,0,0,0,0,0,0,0,3,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,2], [2,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,2], [2,0,0,0,0,0,0,0,0,0,3,3,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,3,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,2], [2,0,0,0,0,0,0,0,0,0,0,0,3,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,3,0,0,0,0,0,0,0,3,0,0,0,0,0,2], [2,0,0,0,0,0,0,0,0,0,0,0,0,3,3,3,3,3,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,3,3,3,0,0,3,0,0,0,0,0,0,2], [2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,3,3,3,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,3,3,0,0,0,0,0,0,0,2], [2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2], [2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2], [2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2], [2,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2], [2,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,3,3,3,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2], [2,0,0,0,0,3,0,0,0,0,0,0,0,0,3,3,3,3,0,0,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2], [2,0,0,0,0,3,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2], [2,0,0,0,0,3,3,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2], [2,0,0,0,0,0,3,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2], [2,0,0,0,0,0,3,3,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2], [2,0,0,0,0,0,0,3,3,3,3,3,3,3,3,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2], [2,0,0,0,0,0,0,0,0,0,0,0,0,3,3,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,3,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2], [2,0,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,3,3,0,0,0,0,0,0,0,0,3,3,3,0,0,0,0,0,0,0,0,0,0,0,0,0,2], [2,0,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,3,3,3,0,0,0,0,0,0,0,0,0,0,0,2], [2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2], [2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2], [2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2], [2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2], [2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2], [2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2], [2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2], [2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2], [2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2] ]; } } board = loadMap(1); enterfor (y = 0; y <= viewHeight; y++) { for (x = 0; x <= viewWidth; x++) { var theX = x * 32; var theY = y * 32; context.drawImage(mapTiles[board[y+viewY][x+viewX]], theX, theY, 32, 32); } } And here is the code I use for player movement: canvas.addEventListener('keydown', function(e) { console.log(e); var key = null; switch (e.which) { case 37: // Left if (playerX > 0) playerX--; break; case 38: // Up if (playerY > 0) playerY--; break; case 39: // Right if (playerX < worldWidth) playerX++; break; case 40: // Down if (playerY < worldHeight) playerY++; break; } viewX = playerX - Math.floor(0.5 * viewWidth); if (viewX < 0) viewX = 0; if (viewX+viewWidth > worldWidth) viewX = worldWidth - viewWidth; viewY = playerY - Math.floor(0.5 * viewHeight); if (viewY < 0) viewY = 0; if (viewY+viewHeight > worldHeight) viewY = worldHeight - viewHeight; }, false); What I am looking for is a method for when the player lands on tile 3 he loses health. I have tried to use this in the player movement but it doesnt seem to work e.g the left movement: case 37: // Left if (playerX > 0) playerX--; if(board[x2 - 1] == 3) { health--; playerX--; }

    Read the article

  • WPF Blurry Images - Bitmap Class

    - by Luke
    I am using the following sample at http://blogs.msdn.com/dwayneneed/archive/2007/10/05/blurry-bitmaps.aspx within VB.NET. The code is shown below. I am having a problem when my application loads the CPU is pegging 50-70%. I have determined that the problem is with the Bitmap class. The OnLayoutUpdated() method is calling the InvalidateVisual() continously. This is because some points are not returning as equal but rather, Point(0.0,-0.5) Can anyone see any bugs within this code or know a better implmentation for pixel snapping a Bitmap image so it is not blurry? p.s. The sample code was in C#, however I believe that it was converted correctly. Imports System Imports System.Collections.Generic Imports System.Windows Imports System.Windows.Media Imports System.Windows.Media.Imaging Class Bitmap Inherits FrameworkElement ' Use FrameworkElement instead of UIElement so Data Binding works as expected Private _sourceDownloaded As EventHandler Private _sourceFailed As EventHandler(Of ExceptionEventArgs) Private _pixelOffset As Windows.Point Public Sub New() _sourceDownloaded = New EventHandler(AddressOf OnSourceDownloaded) _sourceFailed = New EventHandler(Of ExceptionEventArgs)(AddressOf OnSourceFailed) AddHandler LayoutUpdated, AddressOf OnLayoutUpdated End Sub Public Shared ReadOnly SourceProperty As DependencyProperty = DependencyProperty.Register("Source", GetType(BitmapSource), GetType(Bitmap), New FrameworkPropertyMetadata(Nothing, FrameworkPropertyMetadataOptions.AffectsRender Or FrameworkPropertyMetadataOptions.AffectsMeasure, New PropertyChangedCallback(AddressOf Bitmap.OnSourceChanged))) Public Property Source() As BitmapSource Get Return DirectCast(GetValue(SourceProperty), BitmapSource) End Get Set(ByVal value As BitmapSource) SetValue(SourceProperty, value) End Set End Property Public Shared Function FindParentWindow(ByVal child As DependencyObject) As Window Dim parent As DependencyObject = VisualTreeHelper.GetParent(child) 'Check if this is the end of the tree If parent Is Nothing Then Return Nothing End If Dim parentWindow As Window = TryCast(parent, Window) If parentWindow IsNot Nothing Then Return parentWindow Else ' Use recursion until it reaches a Window Return FindParentWindow(parent) End If End Function Public Event BitmapFailed As EventHandler(Of ExceptionEventArgs) ' Return our measure size to be the size needed to display the bitmap pixels. ' ' Use MeasureOverride instead of MeasureCore so Data Binding works as expected. ' Protected Overloads Overrides Function MeasureCore(ByVal availableSize As Size) As Size Protected Overloads Overrides Function MeasureOverride(ByVal availableSize As Size) As Size Dim measureSize As New Size() Dim bitmapSource As BitmapSource = Source If bitmapSource IsNot Nothing Then Dim ps As PresentationSource = PresentationSource.FromVisual(Me) If Me.VisualParent IsNot Nothing Then Dim window As Window = window.GetWindow(Me.VisualParent) If window IsNot Nothing Then ps = PresentationSource.FromVisual(window.GetWindow(Me.VisualParent)) ElseIf FindParentWindow(Me) IsNot Nothing Then ps = PresentationSource.FromVisual(FindParentWindow(Me)) End If End If ' If ps IsNot Nothing Then Dim fromDevice As Matrix = ps.CompositionTarget.TransformFromDevice Dim pixelSize As New Vector(bitmapSource.PixelWidth, bitmapSource.PixelHeight) Dim measureSizeV As Vector = fromDevice.Transform(pixelSize) measureSize = New Size(measureSizeV.X, measureSizeV.Y) Else measureSize = New Size(bitmapSource.PixelWidth, bitmapSource.PixelHeight) End If End If Return measureSize End Function Protected Overloads Overrides Sub OnRender(ByVal dc As DrawingContext) Dim bitmapSource As BitmapSource = Me.Source If bitmapSource IsNot Nothing Then _pixelOffset = GetPixelOffset() ' Render the bitmap offset by the needed amount to align to pixels. dc.DrawImage(bitmapSource, New Rect(_pixelOffset, DesiredSize)) End If End Sub Private Shared Sub OnSourceChanged(ByVal d As DependencyObject, ByVal e As DependencyPropertyChangedEventArgs) Dim bitmap As Bitmap = DirectCast(d, Bitmap) Dim oldValue As BitmapSource = DirectCast(e.OldValue, BitmapSource) Dim newValue As BitmapSource = DirectCast(e.NewValue, BitmapSource) If ((oldValue IsNot Nothing) AndAlso (bitmap._sourceDownloaded IsNot Nothing)) AndAlso (Not oldValue.IsFrozen AndAlso (TypeOf oldValue Is BitmapSource)) Then RemoveHandler DirectCast(oldValue, BitmapSource).DownloadCompleted, bitmap._sourceDownloaded RemoveHandler DirectCast(oldValue, BitmapSource).DownloadFailed, bitmap._sourceFailed ' ((BitmapSource)newValue).DecodeFailed -= bitmap._sourceFailed; // 3.5 End If If ((newValue IsNot Nothing) AndAlso (TypeOf newValue Is BitmapSource)) AndAlso Not newValue.IsFrozen Then AddHandler DirectCast(newValue, BitmapSource).DownloadCompleted, bitmap._sourceDownloaded AddHandler DirectCast(newValue, BitmapSource).DownloadFailed, bitmap._sourceFailed ' ((BitmapSource)newValue).DecodeFailed += bitmap._sourceFailed; // 3.5 End If End Sub Private Sub OnSourceDownloaded(ByVal sender As Object, ByVal e As EventArgs) InvalidateMeasure() InvalidateVisual() End Sub Private Sub OnSourceFailed(ByVal sender As Object, ByVal e As ExceptionEventArgs) Source = Nothing ' setting a local value seems scetchy... RaiseEvent BitmapFailed(Me, e) End Sub Private Sub OnLayoutUpdated(ByVal sender As Object, ByVal e As EventArgs) ' This event just means that layout happened somewhere. However, this is ' what we need since layout anywhere could affect our pixel positioning. Dim pixelOffset As Windows.Point = GetPixelOffset() If Not AreClose(pixelOffset, _pixelOffset) Then InvalidateVisual() End If End Sub ' Gets the matrix that will convert a Windows.Point from "above" the ' coordinate space of a visual into the the coordinate space ' "below" the visual. Private Function GetVisualTransform(ByVal v As Visual) As Matrix If v IsNot Nothing Then Dim m As Matrix = Matrix.Identity Dim transform As Transform = VisualTreeHelper.GetTransform(v) If transform IsNot Nothing Then Dim cm As Matrix = transform.Value m = Matrix.Multiply(m, cm) End If Dim offset As Vector = VisualTreeHelper.GetOffset(v) m.Translate(offset.X, offset.Y) Return m End If Return Matrix.Identity End Function Private Function TryApplyVisualTransform(ByVal Point As Windows.Point, ByVal v As Visual, ByVal inverse As Boolean, ByVal throwOnError As Boolean, ByRef success As Boolean) As Windows.Point success = True If v IsNot Nothing Then Dim visualTransform As Matrix = GetVisualTransform(v) If inverse Then If Not throwOnError AndAlso Not visualTransform.HasInverse Then success = False Return New Windows.Point(0, 0) End If visualTransform.Invert() End If Point = visualTransform.Transform(Point) End If Return Point End Function Private Function ApplyVisualTransform(ByVal Point As Windows.Point, ByVal v As Visual, ByVal inverse As Boolean) As Windows.Point Dim success As Boolean = True Return TryApplyVisualTransform(Point, v, inverse, True, success) End Function Private Function GetPixelOffset() As Windows.Point Dim pixelOffset As New Windows.Point() Dim ps As PresentationSource = PresentationSource.FromVisual(Me) If ps IsNot Nothing Then Dim rootVisual As Visual = ps.RootVisual ' Transform (0,0) from this element up to pixels. pixelOffset = Me.TransformToAncestor(rootVisual).Transform(pixelOffset) pixelOffset = ApplyVisualTransform(pixelOffset, rootVisual, False) pixelOffset = ps.CompositionTarget.TransformToDevice.Transform(pixelOffset) ' Round the origin to the nearest whole pixel. pixelOffset.X = Math.Round(pixelOffset.X) pixelOffset.Y = Math.Round(pixelOffset.Y) ' Transform the whole-pixel back to this element. pixelOffset = ps.CompositionTarget.TransformFromDevice.Transform(pixelOffset) pixelOffset = ApplyVisualTransform(pixelOffset, rootVisual, True) pixelOffset = rootVisual.TransformToDescendant(Me).Transform(pixelOffset) End If Return pixelOffset End Function Private Function AreClose(ByVal Point1 As Windows.Point, ByVal Point2 As Windows.Point) As Boolean Return AreClose(Point1.X, Point2.X) AndAlso AreClose(Point1.Y, Point2.Y) End Function Private Function AreClose(ByVal value1 As Double, ByVal value2 As Double) As Boolean If value1 = value2 Then Return True End If Dim delta As Double = value1 - value2 Return ((delta < 0.00000153) AndAlso (delta > -0.00000153)) End Function End Class

    Read the article

  • ASPX ajax form post help

    - by StealthRT
    Hey all, i have this peice of code that allows a user to select a jpg image, resize it and uploads it to the server driectory. The problem being is that it reloads the aspx page when it saves the image. My question is-is there any way to do this same thing but with ajax so that it doesn't leave the page after submitting it? I've done this pleanty of times with classic asp pages but never with a aspx page. Here is the code for the ASPX page: <%@ Page Trace="False" Language="vb" aspcompat="false" debug="true" validateRequest="false"%> <%@ Import Namespace=System.Drawing %> <%@ Import Namespace=System.Drawing.Imaging %> <%@ Import Namespace=System.Drawing.Text %> <%@ Import Namespace=System %> <%@ Import Namespace=System.IO %> <%@ Import Namespace=System.Web %> <%@ Import Namespace=System.ServiceProcess %> <%@ Import Namespace=Microsoft.Data.Odbc %> <%@ Import Namespace=System.Data.Odbc %> <%@ Import Namespace=MySql.Data.MySqlClient %> <%@ Import Namespace=MySql.Data %> <%@ Import Namespace=System.Drawing.Drawing2D %> <%@ Import Namespace="System.Data" %> <%@ Import Namespace="System.Data.ADO" %> <%@ Import Namespace=ADODB %> <SCRIPT LANGUAGE="VBScript" runat="server"> const Lx = 200 const Ly = 60 const upload_dir = "/img/avatar/" const upload_original = "tmpAvatar" const upload_thumb = "thumb" const upload_max_size = 256 dim fileExt dim newWidth, newHeight as integer dim l2 dim fileFld as HTTPPostedFile Dim originalimg As System.Drawing.Image dim msg dim upload_ok as boolean </script> <% Dim theID, theEmail, maleOrFemale theID = Request.QueryString("ID") theEmail = Request.QueryString("eMail") maleOrFemale = Request.QueryString("MF") randomize() upload_ok = false if lcase(Request.ServerVariables("REQUEST_METHOD"))="post" then fileFld = request.files(0) if fileFld.ContentLength > upload_max_size * 1024 then msg = "Sorry, the image must be less than " & upload_max_size & "Kb" else try fileExt = System.IO.Path.GetExtension(fileFld.FileName).ToLower() if fileExt = ".jpg" then originalImg = System.Drawing.Image.FromStream(fileFld.InputStream) if originalImg.Height > Ly then newWidth = Ly * (originalImg.Width / originalImg.Height) newHeight = Ly end if Dim thumb As New Bitmap(newWidth, newHeight) Dim gr_dest As Graphics = Graphics.FromImage(thumb) dim sb = new SolidBrush(System.Drawing.Color.White) gr_dest.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality gr_dest.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality gr_dest.FillRectangle(sb, 0, 0, thumb.Width, thumb.Height) gr_dest.DrawImage(originalImg, 0, 0, thumb.Width, thumb.Height) try originalImg.save(Server.MapPath(upload_dir & upload_original & fileExt), originalImg.rawformat) thumb.save(Server.MapPath(upload_dir & theID & fileExt), originalImg.rawformat) msg = "Uploaded " & fileFld.FileName & " to " & Server.MapPath(upload_dir & upload_original & fileExt) upload_ok = true File.Delete(Server.MapPath(upload_dir & upload_original & fileExt)) catch msg = "Sorry, there was a problem saving your avatar. Please try again." end try if not thumb is nothing then thumb.Dispose() thumb = nothing end if else msg = "That image does not seem to be a JPG. Upload only JPG images." end if catch msg = "That image does not seem to be a JPG." end try end if if not originalImg is nothing then originalImg.Dispose() originalImg = nothing end if end if %><head> <meta http-equiv="pragma" content="no-cache" /> </head> <html> <script type="text/javascript" src="js/jquery-1.3.min.js"></script> <form enctype="multipart/form-data" method="post" runat="server" id="sendImg"> <input type="file" name="upload_file" id="upload_file" style="-moz-opacity: 0; opacity:0; filter: alpha(opacity=0); margin-top: 5px; float:left; cursor:pointer;" onChange="$('#sendImg').submit();" > <input type="submit" value="Upload" style="visibility:hidden; display:none;"> </form> </body> </html> Any help would be great! :o) David

    Read the article

  • Java image conversion to RGB565

    - by Vladimir
    I try to convert image to RGB565 format. I read this image: BufferedImage bufImg = ImageIO.read(imagePathFile); sendImg = new BufferedImage(CONTROLLER_LCD_WIDTH/*320*/, CONTROLLER_LCD_HEIGHT/*240*/, BufferedImage.TYPE_USHORT_565_RGB); sendImg .getGraphics().drawImage(bufImg, 0, 0, CONTROLLER_LCD_WIDTH/*320*/, CONTROLLER_LCD_HEIGHT/*240*/, null); Here is it: Then I convert it to RGB565: int numByte=0; byte[] OutputImageArray = new byte[CONTROLLER_LCD_WIDTH*CONTROLLER_LCD_HEIGHT*2]; int i=0; int j=0; int len = OutputImageArray.length; for (i=0;i<CONTROLLER_LCD_WIDTH;i++) { for (j=0;j<CONTROLLER_LCD_HEIGHT;j++) { Color c = new Color(sendImg.getRGB(i, j)); int aRGBpix = sendImg.getRGB(i, j); int alpha; int red = c.getRed(); int green = c.getGreen(); int blue = c.getBlue(); //RGB888 red = (aRGBpix >> 16) & 0x0FF; green = (aRGBpix >> 8) & 0x0FF; blue = (aRGBpix >> 0) & 0x0FF; alpha = (aRGBpix >> 24) & 0x0FF; //RGB565 red = red >> 3; green = green >> 2; blue = blue >> 3; //A pixel is represented by a 4-byte (32 bit) integer, like so: //00000000 00000000 00000000 11111111 //^ Alpha ^Red ^Green ^Blue //Converting to RGB565 short pixel_to_send = 0; int pixel_to_send_int = 0; pixel_to_send_int = (red << 11) | (green << 5) | (blue); pixel_to_send = (short) pixel_to_send_int; //dividing into bytes byte byteH=(byte)((pixel_to_send >> 8) & 0x0FF); byte byteL=(byte)(pixel_to_send & 0x0FF); //Writing it to array - High-byte is second OutputImageArray[numByte]=byteH; OutputImageArray[numByte+1]=byteL; numByte+=2; } } Then I try to restore this from resulting array OutputImageArray: i=0; j=0; numByte=0; BufferedImage NewImg = new BufferedImage(CONTROLLER_LCD_WIDTH, CONTROLLER_LCD_HEIGHT, BufferedImage.TYPE_USHORT_565_RGB); for (i=0;i<CONTROLLER_LCD_WIDTH;i++) { for (j=0;j<CONTROLLER_LCD_HEIGHT;j++) { int curPixel=0; int alpha=0x0FF; int red; int green; int blue; byte byteL=0; byte byteH=0; byteH = OutputImageArray[numByte]; byteL = OutputImageArray[numByte+1]; curPixel= (byteH << 8) | (byteL); //RGB565 red = (curPixel >> (6+5)) & 0x01F; green = (curPixel >> 5) & 0x03F; blue = (curPixel) & 0x01F; //RGB888 red = red << 3; green = green << 2; blue = blue << 3; //aRGB curPixel = 0; curPixel = (alpha << 24) | (red << 16) | (green << 8) | (blue); NewImg.setRGB(i, j, curPixel); numByte+=2; } } I output this restored image. But I see that it looks very poor. I expected the lost of pictures quality. But as I thought, this picture has to have almost the same quality as the previous picture. - Is it right? Is my code right?

    Read the article

  • JPanel Layout Image Cutoff

    - by Trizicus
    I am adding images to a JPanel but the images are getting cut off. I was originally trying BorderLayout but that only worked for one image and adding others added image cut-off. So I switched to other layouts and the best and closest I could get was BoxLayout however that adds a very large cut-off which is not acceptable either. So basically; How can I add images (from a custom JComponent) to a custom JPanel without bad effects such as the one present in the code. Custom JPanel: import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import javax.swing.BoxLayout; import javax.swing.JPanel; import javax.swing.Timer; public class GraphicsPanel extends JPanel implements MouseListener { private Entity test; private Timer timer; private long startTime = 0; private int numFrames = 0; private float fps = 0.0f; GraphicsPanel() { test = new Entity("test.png"); Thread t1 = new Thread(test); t1.start(); Entity ent2 = new Entity("images.jpg"); ent2.setX(150); ent2.setY(150); Thread t2 = new Thread(ent2); t2.start(); Entity ent3 = new Entity("test.png"); ent3.setX(0); ent3.setY(150); Thread t3 = new Thread(ent3); t3.start(); //ESSENTIAL setLayout(new BoxLayout(this, BoxLayout.X_AXIS)); add(test); add(ent2); add(ent3); //GAMELOOP timer = new Timer(30, new Gameloop(this)); timer.start(); addMouseListener(this); } @Override public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D) g.create(); g2.setClip(0, 0, getWidth(), getHeight()); g2.setColor(Color.BLACK); g2.drawString("FPS: " + fps, 1, 15); } public void getFPS() { ++numFrames; if (startTime == 0) { startTime = System.currentTimeMillis(); } else { long currentTime = System.currentTimeMillis(); long delta = (currentTime - startTime); if (delta > 1000) { fps = (numFrames * 1000) / delta; numFrames = 0; startTime = currentTime; } } } public void mouseClicked(MouseEvent e) {} public void mousePressed(MouseEvent e) {} public void mouseReleased(MouseEvent e) {} public void mouseEntered(MouseEvent e) { } public void mouseExited(MouseEvent e) { } class Gameloop implements ActionListener { private GraphicsPanel gp; Gameloop(GraphicsPanel gp) { this.gp = gp; } public void actionPerformed(ActionEvent e) { try { gp.getFPS(); gp.repaint(); } catch (Exception ez) { } } } } Main class: import java.awt.EventQueue; import javax.swing.JFrame; public class MainWindow { public static void main(String[] args) { new MainWindow(); } private JFrame frame; private GraphicsPanel gp = new GraphicsPanel(); MainWindow() { EventQueue.invokeLater(new Runnable() { public void run() { frame = new JFrame("Graphics Practice"); frame.setSize(680, 420); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.add(gp); } }); } } Custom JComponent import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import javax.imageio.ImageIO; import javax.swing.JComponent; public class Entity extends JComponent implements Runnable { private BufferedImage bImg; private int x = 0; private int y = 0; private int entityWidth, entityHeight; private String filename; Entity(String filename) { this.filename = filename; } public void run() { bImg = loadBImage(filename); entityWidth = bImg.getWidth(); entityHeight = bImg.getHeight(); setPreferredSize(new Dimension(entityWidth, entityHeight)); } @Override public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2d = (Graphics2D) g.create(); g2d.drawImage(bImg, x, y, null); g2d.dispose(); } public BufferedImage loadBImage(String filename) { try { bImg = ImageIO.read(getClass().getResource(filename)); } catch (Exception e) { } return bImg; } public int getEntityWidth() { return entityWidth; } public int getEntityHeight() { return entityHeight; } public int getX() { return x; } public int getY() { return y; } public void setX(int x) { this.x = x; } public void setY(int y) { this.y = y; } }

    Read the article

  • capturing video from ip camera

    - by Ruby
    I am trying to capture video from ip camera into my application , its giving exception com.sun.image.codec.jpeg.ImageFormatException: Not a JPEG file: starts with 0x0d 0x0a at sun.awt.image.codec.JPEGImageDecoderImpl.readJPEGStream(Native Method) at sun.awt.image.codec.JPEGImageDecoderImpl.decodeAsBufferedImage(Unknown Source) at test.AxisCamera1.readJPG(AxisCamera1.java:130) at test.AxisCamera1.readMJPGStream(AxisCamera1.java:121) at test.AxisCamera1.readStream(AxisCamera1.java:100) at test.AxisCamera1.run(AxisCamera1.java:171) at java.lang.Thread.run(Unknown Source) its giving exception at image = decoder.decodeAsBufferedImage(); Here is the code i am trying private static final long serialVersionUID = 1L; public boolean useMJPGStream = true; public String jpgURL = "http://ip here/video.cgi/jpg/image.cgi?resolution=640×480"; public String mjpgURL = "http://ip here /video.cgi/mjpg/video.cgi?resolution=640×480"; DataInputStream dis; private BufferedImage image = null; public Dimension imageSize = null; public boolean connected = false; private boolean initCompleted = false; HttpURLConnection huc = null; Component parent; /** Creates a new instance of AxisCamera */ public AxisCamera1(Component parent_) { parent = parent_; } public void connect() { try { URL u = new URL(useMJPGStream ? mjpgURL : jpgURL); huc = (HttpURLConnection) u.openConnection(); // System.out.println(huc.getContentType()); InputStream is = huc.getInputStream(); connected = true; BufferedInputStream bis = new BufferedInputStream(is); dis = new DataInputStream(bis); if (!initCompleted) initDisplay(); } catch (IOException e) { // incase no connection exists wait and try // again, instead of printing the error try { huc.disconnect(); Thread.sleep(60); } catch (InterruptedException ie) { huc.disconnect(); connect(); } connect(); } catch (Exception e) { ; } } public void initDisplay() { // setup the display if (useMJPGStream) readMJPGStream(); else { readJPG(); disconnect(); } imageSize = new Dimension(image.getWidth(this), image.getHeight(this)); setPreferredSize(imageSize); parent.setSize(imageSize); parent.validate(); initCompleted = true; } public void disconnect() { try { if (connected) { dis.close(); connected = false; } } catch (Exception e) { ; } } public void paint(Graphics g) { // used to set the image on the panel if (image != null) g.drawImage(image, 0, 0, this); } public void readStream() { // the basic method to continuously read the // stream try { if (useMJPGStream) { while (true) { readMJPGStream(); parent.repaint(); } } else { while (true) { connect(); readJPG(); parent.repaint(); disconnect(); } } } catch (Exception e) { ; } } public void readMJPGStream() { // preprocess the mjpg stream to remove the // mjpg encapsulation readLine(3, dis); // discard the first 3 lines readJPG(); readLine(2, dis); // discard the last two lines } public void readJPG() { // read the embedded jpeg image try { JPEGImageDecoder decoder = JPEGCodec.createJPEGDecoder(dis); image = decoder.decodeAsBufferedImage(); } catch (Exception e) { e.printStackTrace(); disconnect(); } } public void readLine(int n, DataInputStream dis) { // used to strip out the // header lines for (int i = 0; i < n; i++) { readLine(dis); } } public void readLine(DataInputStream dis) { try { boolean end = false; String lineEnd = "\n"; // assumes that the end of the line is marked // with this byte[] lineEndBytes = lineEnd.getBytes(); byte[] byteBuf = new byte[lineEndBytes.length]; while (!end) { dis.read(byteBuf, 0, lineEndBytes.length); String t = new String(byteBuf); System.out.print(t); // uncomment if you want to see what the // lines actually look like if (t.equals(lineEnd)) end = true; } } catch (Exception e) { e.printStackTrace(); } } public void run() { System.out.println("in Run..................."); connect(); readStream(); } @SuppressWarnings("deprecation") public static void main(String[] args) { JFrame jframe = new JFrame(); jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); AxisCamera1 axPanel = new AxisCamera1(jframe); new Thread(axPanel).start(); jframe.getContentPane().add(axPanel); jframe.pack(); jframe.show(); } } Any suggestions what I am doing wrong here??

    Read the article

  • how to run/compile java code from JTextArea at Runtime? ----urgent!!! college project

    - by Lokesh Kumar
    I have a JInternalFrame painted with a BufferedImage and contained in the JDesktopPane of a JFrame.I also have a JTextArea where i want to write some java code (function) that takes the current JInternalFrame's painted BufferedImage as an input and after doing some manipulation on this input it returns another manipulated BufferedImage that paints the JInternalFrame with new manipulated Image again!!. Manipulation java code of JTextArea:- public BufferedImage customOperation(BufferedImage CurrentInputImg) { Color colOld; Color colNew; BufferedImage manipulated=new BufferedImage(CurrentInputImg.getWidth(),CurrentInputImg.getHeight(),BufferedImage.TYPE_INT_ARGB); //make all Red pixels of current image black for(int i=0;i< CurrentInputImg.getWidth();i++) { for(int j=0;j< CurrentInputImg.getHeight(),j++) { colOld=new Color(CurrentInputImg.getRGB(i,j)); colNew=new Color(0,colOld.getGreen(),colOld.getBlue(),colOld.getAlpha()); manipulated.setRGB(i,j,colNew.getRGB()); } } return manipulated; } so,how can i run/compile this JTextArea java code at runtime and get a new manipulated image for painting on JInternalFrame???????   Here is my Main class: (This class is not actual one but i have created it for u for basic interfacing containing JTextArea,JInternalFrame,Apply Button) import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.event.*; import javax.swing.JInternalFrame; import javax.swing.JDesktopPane; import java.awt.image.*; import javax.imageio.*; import java.io.*; import java.io.File; import java.util.*; class MyCustomOperationSystem extends JFrame **{** public JInternalFrame ImageFrame; public BufferedImage CurrenFrameImage; public MyCustomOperationSystem() **{** setTitle("My Custom Image Operations"); setSize((int)Toolkit.getDefaultToolkit().getScreenSize().getWidth(),(int)Toolkit.getDefaultToolkit().getScreenSize().getHeight()); JDesktopPane desktop=new JDesktopPane(); desktop.setPreferredSize(new Dimension((int)Toolkit.getDefaultToolkit().getScreenSize().getWidth(),(int)Toolkit.getDefaultToolkit().getScreenSize().getHeight())); try{ CurrenFrameImage=ImageIO.read(new File("c:/Lokesh.png")); }catch(Exception exp) { System.out.println("Error in Loading Image"); } ImageFrame=new JInternalFrame("Image Frame",true,true,false,true); ImageFrame.setMinimumSize(new Dimension(CurrenFrameImage.getWidth()+10,CurrenFrameImage.getHeight()+10)); ImageFrame.getContentPane().add(CreateImagePanel()); ImageFrame.setLayer(1); ImageFrame.setLocation(100,100); ImageFrame.setVisible(true); desktop.setOpaque(true); desktop.setBackground(Color.darkGray); desktop.add(ImageFrame); this.getContentPane().setLayout(new BorderLayout()); this.getContentPane().add("Center",desktop); this.getContentPane().add("South",ControlPanel()); pack(); setVisible(true); **}** public JPanel CreateImagePanel(){ JPanel tempPanel=new JPanel(){ public void paintComponent(Graphics g) { g.drawImage(CurrenFrameImage,0,0,this); } }; tempPanel.setPreferredSize(new Dimension(CurrenFrameImage.getWidth(),CurrenFrameImage.getHeight())); return tempPanel; } public JPanel ControlPanel(){ JPanel controlPan=new JPanel(new FlowLayout(FlowLayout.LEFT)); JButton customOP=new JButton("Custom Operation"); customOP.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent evnt){ JFrame CodeFrame=new JFrame("Write your Code Here"); JTextArea codeArea=new JTextArea("Your Java Code Here",100,70); JScrollPane codeScrollPan=new JScrollPane(codeArea,ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS); CodeFrame.add(codeScrollPan); CodeFrame.setVisible(true); } }); JButton Apply=new JButton("Apply Code"); Apply.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent event){ // What should I do!!! Here!!!!!!!!!!!!!!! } }); controlPan.add(customOP); controlPan.add(Apply); return controlPan; } public static void main(String s[]) { new MyCustomOperationSystem(); } } Note: in above class JInternalFrame (ImageFrame) is not visible even i have declared it visible. so, ImageFrame is not visible while compiling and running above class. U have to identify this problem before running it.

    Read the article

  • Why cant i draw an elipse in with code?

    - by bvivek88
    package test; import java.awt.*; import java.awt.event.*; import java.awt.geom.Ellipse2D; import java.awt.image.BufferedImage; import javax.swing.*; public class test_bmp extends JPanel implements MouseListener,MouseMotionListener,ActionListener { static BufferedImage image; Color color; Point start=new Point(); Point end =new Point(); JButton elipse=new JButton("Elipse"); JButton rectangle=new JButton("Rectangle"); JButton line=new JButton("Line"); String selected; public test_bmp() { color = Color.black; setBorder(BorderFactory.createLineBorder(Color.black)); addMouseListener(this); addMouseMotionListener(this); } public void paintComponent(Graphics g) { //super.paintComponent(g); g.drawImage(image, 0, 0, this); Graphics2D g2 = (Graphics2D)g; g2.setPaint(Color.black); if(selected=="elipse") { g2.drawOval(start.x, start.y, (end.x-start.x),(end.y-start.y)); System.out.println("Start : "+start.x+","+start.y); System.out.println("End : "+end.x+","+end.y); } if(selected=="line") g2.drawLine(start.x,start.y,end.x,end.y); } //Draw on Buffered image public void draw() { Graphics2D g2 = image.createGraphics(); g2.setPaint(color); System.out.println("draw"); if(selected=="line") g2.drawLine(start.x, start.y, end.x, end.y); if(selected=="elipse") { g2.drawOval(start.x, start.y, (end.x-start.x),(end.y-start.y)); System.out.println("Start : "+start.x+","+start.y); System.out.println("End : "+end.x+","+end.y); } repaint(); g2.dispose(); } public JPanel addButtons() { JPanel buttonpanel=new JPanel(); buttonpanel.setBackground(color.lightGray); buttonpanel.setLayout(new BoxLayout(buttonpanel,BoxLayout.Y_AXIS)); elipse.addActionListener(this); rectangle.addActionListener(this); line.addActionListener(this); buttonpanel.add(elipse); buttonpanel.add(Box.createRigidArea(new Dimension(15,15))); buttonpanel.add(rectangle); buttonpanel.add(Box.createRigidArea(new Dimension(15,15))); buttonpanel.add(line); return buttonpanel; } public static void main(String args[]) { test_bmp application=new test_bmp(); //Main window JFrame frame=new JFrame("Whiteboard"); frame.setLayout(new BorderLayout()); frame.add(application.addButtons(),BorderLayout.WEST); frame.add(application); //size of the window frame.setSize(600,400); frame.setLocation(0,0); frame.setVisible(true); int w = frame.getWidth(); int h = frame.getHeight(); image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB); Graphics2D g2 = image.createGraphics(); g2.setPaint(Color.white); g2.fillRect(0,0,w,h); g2.dispose(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } @Override public void mouseClicked(MouseEvent arg0) { // TODO Auto-generated method stub } @Override public void mouseEntered(MouseEvent arg0) { // TODO Auto-generated method stub } @Override public void mouseExited(MouseEvent arg0) { // TODO Auto-generated method stub } @Override public void mousePressed(MouseEvent event) { start = event.getPoint(); } @Override public void mouseReleased(MouseEvent event) { end = event.getPoint(); draw(); } @Override public void mouseDragged(MouseEvent e) { end=e.getPoint(); repaint(); } @Override public void mouseMoved(MouseEvent arg0) { // TODO Auto-generated method stub } @Override public void actionPerformed(ActionEvent e) { if(e.getSource()==elipse) selected="elipse"; if(e.getSource()==line) selected="line"; draw(); } } I need to create a paint application, when i draw elipse by dragging mouse from left to right it displays nothing, why?? should i use any other function here?

    Read the article

  • ASp.Net Mvc 1.0 Dynamic Images Returned from Controller taking 154 seconds+ to display in IE8, firef

    - by julian guppy
    I have a curious problem with IE, IIS 6.0 dynamic PNG files and I am baffled as to how to fix.. Snippet from Helper (this returns the URL to the view for requesting the images from my Controller. string url = LinkBuilder.BuildUrlFromExpression(helper.ViewContext.RequestContext, helper.RouteCollection, c = c.FixHeight(ir.Filename, ir.AltText, "FFFFFF")); url = url.Replace("&", "&"); sb.Append(string.Format("<removed id=\"TheImage\" src=\"{0}\" alt=\"\" /", url)+Environment.NewLine); This produces a piece of html as follows:- img id="TheImage" src="/ImgText/FixHeight?sFile=Images%2FUser%2FJulianGuppy%2FMediums%2Fconservatory.jpg&backgroundColour=FFFFFF" alt="" / brackets missing because i cant post an image... even though I dont want to post an image I jsut want to post the markup... sigh Snippet from Controller ImgTextController /// <summary> /// This function fixes the height of the image /// </summary> /// <param name="sFile"></param> /// <param name="alternateText"></param> /// <param name="backgroundColour"></param> /// <returns></returns> [AcceptVerbs(HttpVerbs.Get)] public ActionResult FixHeight(string sFile, string alternateText, string backgroundColour) { #region File if (string.IsNullOrEmpty(sFile)) { return new ImgTextResult(); } // MVC specific change to prepend the new directory if (sFile.IndexOf("Content") == -1) { sFile = "~/Content/" + sFile; } // open the file System.Drawing.Image img; try { img = System.Drawing.Image.FromFile(Server.MapPath(sFile)); } catch { img = null; } // did we fail? if (img == null) { return new ImgTextResult(); } #endregion File #region Width // Sort out the width from the image passed to me Int32 nWidth = img.Width; #endregion Width #region Height Int32 nHeight = img.Height; #endregion Height // What is the ideal height given a width of 2100 this should be 1400. var nIdealHeight = (int)(nWidth / 1.40920096852); // So is the actual height of the image already greater than the ideal height? Int32 nSplit; if (nIdealHeight < nHeight) { // Yes, do nothing, well i need to return the iamge... nSplit = 0; } else { // rob wants to not show the white at the top or bottom, so if we were to crop the image how would be do it // 1. Calculate what the width should be If we dont adjust the heigt var newIdealWidth = (int)(nHeight * 1.40920096852); // 2. This newIdealWidth should be smaller than the existing width... so work out the split on that Int32 newSplit = (nWidth - newIdealWidth) / 2; // 3. Now recrop the image using 0-nHeight as the height (i.e. full height) // but crop the sides so that its the correct aspect ration var newRect = new Rectangle(newSplit, 0, newIdealWidth, nHeight); img = CropImage(img, newRect); nHeight = img.Height; nWidth = img.Width; nSplit = 0; } // No, so I want to place this image on a larger canvas and we do this by Creating a new image to be the size that we want System.Drawing.Image canvas = new Bitmap(nWidth, nIdealHeight, PixelFormat.Format24bppRgb); Graphics g = Graphics.FromImage(canvas); #region Color // Whilst we can set the background colour we shall default to white if (string.IsNullOrEmpty(backgroundColour)) { backgroundColour = "FFFFFF"; } Color bc = ColorTranslator.FromHtml("#" + backgroundColour); #endregion Color // Filling the background (which gives us our broder) Brush backgroundBrush = new SolidBrush(bc); g.FillRectangle(backgroundBrush, -1, -1, nWidth + 1, nIdealHeight + 1); // draw the image at the position var rect = new Rectangle(0, nSplit, nWidth, nHeight); g.DrawImage(img, rect); return new ImgTextResult { Image = canvas, ImageFormat = ImageFormat.Png }; } My ImgTextResult is a class that returns an Action result for me but embedding the image from a memory stream into the response.outputstream. snippet from my ImageResults /// <summary> /// Execute the result /// </summary> /// <param name="context"></param> public override void ExecuteResult(ControllerContext context) { // output context.HttpContext.Response.Clear(); context.HttpContext.Response.ContentType = "image/png"; try { var memStream = new MemoryStream(); Image.Save(memStream, ImageFormat.Png); context.HttpContext.Response.BinaryWrite(memStream.ToArray()); context.HttpContext.Response.Flush(); context.HttpContext.Response.Close(); memStream.Dispose(); Image.Dispose(); } catch (Exception ex) { string a = ex.Message; } } Now all of this works locally and lovely, and indeed all of this works on my production server BUT Only for Firefox, Safari, Chrome (and other browsers) IE has a fit and decides that it either wont display the image or it does display the image after approx 154seconds of waiting..... I have made sure my HTML is XHTML compliant, I have made sure I am getting no Routing errors or crashes in my event log on the server.... Now obviously I have been a muppet and have done something wrong... but what I cant fathom is why in development all works fine, and in production all non IE browsers also work fine, but IE 8 using IIS 6.0 production server is having some kind of problem in returning this PNG and I dont have an error to trace... so what I am looking for is guidance as to how I can debug this problem.

    Read the article

  • Image not loading onto JPanel?

    - by None None
    I have been trying to figure out how to add an image to a JPanel as a background, but still have complete control over the placing of JButtons, JLabels, and etc. This is one method I found, but it is crashing and not loading the image or buttons. Here is the code: import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JButton; import java.awt.BorderLayout; import java.awt.FlowLayout; import java.awt.GridLayout; public class PanelDemo extends JFrame { private static final long serialVersionUID = 1L; private JButton btn1 = new JButton("EASY"); private JButton btn2 = new JButton("MEDIUM"); private JButton btn3 = new JButton("HARD"); private JButton btn4 = new JButton("High Score"); public PanelDemo() { super("Image Panel Demo"); JPanel panel = new ImagePanel( new FlowLayout(FlowLayout.CENTER, 50, 180)); JPanel panelbtn = new JPanel(new GridLayout(4, 1)); btn1.setBackground(new java.awt.Color(0, 0, 0)); btn1.setFont(new java.awt.Font("Showcard Gothic", 1, 24)); btn1.setForeground(new java.awt.Color(0, 255, 102)); btn2.setBackground(new java.awt.Color(0, 0, 0)); btn2.setFont(new java.awt.Font("Showcard Gothic", 1, 24)); btn2.setForeground(new java.awt.Color(0, 255, 102)); btn3.setBackground(new java.awt.Color(0, 0, 0)); btn3.setFont(new java.awt.Font("Showcard Gothic", 1, 24)); btn3.setForeground(new java.awt.Color(0, 255, 102)); btn4.setBackground(new java.awt.Color(0, 0, 0)); btn4.setFont(new java.awt.Font("Showcard Gothic", 1, 24)); btn4.setForeground(new java.awt.Color(0, 255, 102)); panel.add(panelbtn); panelbtn.add(btn1); panelbtn.add(btn2); panelbtn.add(btn3); panelbtn.add(btn4); add(panel, BorderLayout.CENTER); setSize(640, 480); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public static void main(String... args) { new PanelDemo().setVisible(true); } } ImagePanel.java import java.awt.Graphics; import java.awt.Image; import java.awt.LayoutManager; import javax.swing.ImageIcon; import javax.swing.JPanel; public class ImagePanel extends JPanel { private static final long serialVersionUID = 1L; String imageFile = "/rsc/img/background.jpg"; public ImagePanel() { super(); } public ImagePanel(String image) { super(); this.imageFile = image; } public ImagePanel(LayoutManager layout) { super(layout); } public void paintComponent(Graphics g) { ImageIcon imageicon = new ImageIcon(getClass().getResource(imageFile)); Image image = imageicon.getImage(); super.paintComponent(g); if (image != null) g.drawImage(image, 0, 0, getWidth(), getHeight(), this); } } Error: Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException at javax.swing.ImageIcon.<init>(Unknown Source) at ImagePanel.paintComponent(ImagePanel.java:27) at javax.swing.JComponent.paint(Unknown Source) at javax.swing.JComponent.paintChildren(Unknown Source) at javax.swing.JComponent.paint(Unknown Source) at javax.swing.JComponent.paintChildren(Unknown Source) at javax.swing.JComponent.paint(Unknown Source) at javax.swing.JLayeredPane.paint(Unknown Source) at javax.swing.JComponent.paintChildren(Unknown Source) at javax.swing.JComponent.paintToOffscreen(Unknown Source) at javax.swing.RepaintManager$PaintManager.paintDoubleBuffered(Unknown Source) at javax.swing.RepaintManager$PaintManager.paint(Unknown Source) at javax.swing.RepaintManager.paint(Unknown Source) at javax.swing.JComponent.paint(Unknown Source) at java.awt.GraphicsCallback$PaintCallback.run(Unknown Source) at sun.awt.SunGraphicsCallback.runOneComponent(Unknown Source) at sun.awt.SunGraphicsCallback.runComponents(Unknown Source) at java.awt.Container.paint(Unknown Source) at java.awt.Window.paint(Unknown Source) at javax.swing.RepaintManager$3.run(Unknown Source) at javax.swing.RepaintManager$3.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source) at javax.swing.RepaintManager.paintDirtyRegions(Unknown Source) at javax.swing.RepaintManager.paintDirtyRegions(Unknown Source) at javax.swing.RepaintManager.prePaintDirtyRegions(Unknown Source) at javax.swing.RepaintManager.access$1000(Unknown Source) at javax.swing.RepaintManager$ProcessingRunnable.run(Unknown Source) at java.awt.event.InvocationEvent.dispatch(Unknown Source) at java.awt.EventQueue.dispatchEventImpl(Unknown Source) at java.awt.EventQueue.access$200(Unknown Source) at java.awt.EventQueue$3.run(Unknown Source) at java.awt.EventQueue$3.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source) at java.awt.EventQueue.dispatchEvent(Unknown Source) at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source) at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source) at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source) at java.awt.EventDispatchThread.pumpEvents(Unknown Source) at java.awt.EventDispatchThread.pumpEvents(Unknown Source) at java.awt.EventDispatchThread.run(Unknown Source) Also, if anyone knows of a better way to put a background image on a JPanel, pease do tell. Thank you in advance.

    Read the article

  • Threads to make video out of images

    - by masood
    updates: I think/ suspect the imageIO is not thread safe. shared by all threads. the read() call might use resources that are also shared. Thus it will give the performance of a single thread no matter how many threads used. ? if its correct . what is the solution (in practical code) Single request and response model at one time do not utilizes full network/internet bandwidth, thus resulting in low performance. (benchmark is of half speed utilization or even lower) This is to make a video out of an IP cam that gives a new image on each request. http://149.5.43.10:8001/snapshot.jpg It makes a delay of 3 - 8 seconds no matter what I do. Changed thread no. and thread time intervals, debugged the code by System.out.println statements to see if threads work. All seems normal. Any help? Please show some practical code. You may modify mine. This code works (javascript) with much smoother frame rate and max bandwidth usage. but the later code (java) dont. same 3 to 8 seconds gap. <!DOCTYPE html> <html> <head> <script type="text/javascript"> (function(){ var img="/*url*/"; var interval=50; var pointer=0; function showImg(image,idx) { if(idx<=pointer) return; document.body.replaceChild(image,document.getElementsByTagName("img")[0]); pointer=idx; preload(); } function preload() { var cache=null,idx=0;; for(var i=0;i<5;i++) { idx=Date.now()+interval*(i+1); cache=new Image(); cache.onload=(function(ele,idx){return function(){showImg(ele,idx);};})(cache,idx); cache.src=img+"?"+idx; } } window.onload=function(){ document.getElementsByTagName("img")[0].onload=preload; document.getElementsByTagName("img")[0].src="/*initial url*/"; }; })(); </script> </head> <body> <img /> </body> </html> and of java (with problem) : package camba; import java.applet.Applet; import java.awt.Button; import java.awt.Graphics; import java.awt.Image; import java.awt.Label; import java.awt.Panel; import java.awt.TextField; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.net.URL; import java.security.Timestamp; import java.util.Date; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import javax.imageio.ImageIO; public class Camba extends Applet implements ActionListener{ Image img; TextField textField; Label label; Button start,stop; boolean terminate = false; long viewTime; public void init(){ label = new Label("please enter camera URL "); add(label); textField = new TextField(30); add(textField); start = new Button("Start"); add(start); start.addActionListener(this); stop = new Button("Stop"); add(stop); stop.addActionListener(this); } public void actionPerformed(ActionEvent e){ Button source = (Button)e.getSource(); if(source.getLabel() == "Start"){ for (int i = 0; i < 7; i++) { myThread(50*i); } System.out.println("start..."); } if(source.getLabel() == "Stop"){ terminate = true; System.out.println("stop..."); } } public void paint(Graphics g) { update(g); } public void update(Graphics g){ try{ viewTime = System.currentTimeMillis(); g.drawImage(img, 100, 100, this); } catch(Exception e) { e.printStackTrace(); } } public void myThread(final int sleepTime){ new Thread(new Runnable() { public void run() { while(!terminate){ try { TimeUnit.MILLISECONDS.sleep(sleepTime); } catch (InterruptedException ex) { ex.printStackTrace(); } long requestTime= 0; Image tempImage = null; try { URL pic = null; requestTime= System.currentTimeMillis(); pic = new URL(getDocumentBase(), textField.getText()); tempImage = ImageIO.read(pic); } catch(Exception e) { e.printStackTrace(); } if(requestTime >= /*last view time*/viewTime){ img = tempImage; Camba.this.repaint(); } } }}).start(); System.out.println("thread started..."); } }

    Read the article

< Previous Page | 6 7 8 9 10 11  | Next Page >