HowTo: Converting a 2D-Image into OpenSCAD

From Wurst-Wasser.net
Revision as of 20:16, 26 August 2015 by Heiko (talk | contribs) (Created page with "Maybe it's just me - but converting some 2D-image for use in OpenSCAD is insanely hard. But why? Converting an image into an DXF for extruding in OpenSCAD is fairly ea...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

Maybe it's just me - but converting some 2D-image for use in OpenSCAD is insanely hard. But why? Converting an image into an DXF for extruding in OpenSCAD is fairly easy, there a plenty of solutions[1] available. But usually I ended up with an DXF that OpenSCAD wasn't able to parse. Sounds familiar? Yes, you ended up with this:

WARNING: Unsupported DXF Entity 'SEQEND' (40) in "Herforder_Brauerei_logo_v6_sw_cropped.dxf". 
WARNING: Unsupported DXF Entity 'VERTEX' (1235) in "Herforder_Brauerei_logo_v6_sw_cropped.dxf". 
WARNING: Unsupported DXF Entity 'POLYLINE' (40) in "Herforder_Brauerei_logo_v6_sw_cropped.dxf". 

Then it came to me: The printer has a very limited resolution when printing - so why bother using vector images? Why not just convert a pixel-based image into a bunch of cube()s?

This is what I came up with after about 20 minutes:

<?php
// $image="/Users/heiko/Documents/3D-Modelle/test.png";

$outputASCII=false;
$outputSCAD=true;

	$im = imagecreatefrompng($image); // http://php.net/manual/de/function.imagecreatefrompng.php

	if ($im)
	{

		$w = imagesx($im); // image width
		$h = imagesy($im); // image height
	
		for($y = 0; $y < $h; $y++) 
		{
		  for($x = 0; $x < $w; $x++) 
		  {
	      	      $rgb = imagecolorat($im, $x, $y);
		      $r = ($rgb >> 16) & 0xFF;
		      $g = ($rgb >> 8) & 0xFF;
		      $b = $rgb & 0xFF;
			  
			  if ($r+$g+$b>(2*256/3))
			  {
				  /* "Weisses Pixel" */
				  if ($outputASCII===true)
				  {
						echo(" ");
				  }
				  else if ($outputSCAD)
				  {
					  // nix
				  }
			  }
			  else
			  {
				  /* "Schwarzes Pixel" */
				  if ($outputASCII===true)
				  {
						echo("#");
				  }
				  else if ($outputSCAD)
				  {
						echo("translate([" . $x . ", " . $y . ", 0]) cube([1, 1, 1]);\n");
				  }
			  }
			} // x
			
		  	if ($outputASCII===true)
		  	{
			  	echo("\n");
		  	}
			
		} // y

		echo("Dimensions:\n");
		echo("x: " . $x . "\n");
		echo("y: " . $y . "\n");
	
		imagedestroy($im); // free resource
	}
	else
	{
		echo("Fail!");
	}


?>

  1. Cloud Services as well as InkScape-Extensions…(Links may follow later :) )