How I improved my workflow with Imagemagick

When working with assets you will often want to change some of them. My personal experience is that I often want to resize images, stitch them together, blur them or convert them from .png to .jpg. When I had to do this I usually sighed, fired up Photoshop, created a batch and then ran everything in my folder through that batch. When I realized I got it wrong I would have to do this again and Photoshop usually crashed at least once in the process as well. Needless to say, I did not enjoy adjusting my assets. Until I didn’t have Photoshop anymore…

Changing workstations

In december I switched from an OS X oriented workplace to an Ubuntu oriented workspace which meant that I didn’t get to have Photoshop on my machine (without jumping through hoops). This wasn’t a problem because I didn’t have to work with assets as much as I used to and when I did I would just ask somebody else to do the tedious tasks for me.

But then I remembered Imagemagick. In the past I’ve used their PHP library to resize images on my webserver, but under the hood that actually uses the Imagemagick command line tool. And since I was working with a Linux machine I figured I could install Imagemagick and use it. And so I did. And it’s beautiful.

Start using Imagemagick

Before you can use Imagemagick you have to install it, go to their install page and find the appropriate version for your machine. Surprise, it turns out they have an OS X version as well. After you’ve installed Imagemagick you should prepare some images to resize.

Resizing images

Resizing images is surprisingly simple. Open up a command line, navigate to the folder where you have your image and type this into your command line.

This will scale your image down to 50% of it’s original size. If you have several images to do this with you might run something like:

Pretty simple, right? You can also scale images proportionally to a pixel value like this:

This will make the image 250px wide and scale the height proportionally. Scaling an image based on height is similar but place the pixel value after the x:

Manipulating image quality

After resizing your images you might want to optimize their quality a bit as well. I usually get extremely high quality assets and they can be as large as 2-3Mb sometimes. After resizing they might already be around the 100Kb, but giving up a little quality can take them down to 60-70Kb. Here’s the command to do that:

Instead of convert I used mogrify for this snippet. Mogrify is used for in-place manipulating of images, so it overwrites your image. If you don’t want this you can just substitute it with convert and use it just like you did earlier.

Wrapping it up

With the commands you’ve learned in this post it should be easy enough to optimize and manipulate your images in the command line. For more examples check out the usage section on the Imagemagick website. I personally feel like using Imagemagick has improved my workflow and I hope it can (and will) do the same for you.

Getting started with Gulp

Let’s talk about tools first

Lately I’ve noticed that many Front-end developers get caught up in tools. Should they use Less, or Sass? Do they code in Sublime or Atom? Or should they pick up Coda 2? What frameworks should they learn? Is Angular worth their time? Or maybe they should go all out on Ember or Backbone.

And then any developer will reach that point where they want to actually compile their css, concatenate their javascript and minify them all. So then there is the question, what do I use for that? Well, there’s many options for that as well! Some prefer Grunt, others pick Gulp and some others turn to Codekit for this. Personally I got started with Codekit and swapped that out for Gulp later on. The reason I chose Gulp over Grunt? I liked the syntax better and people said it was exponentially faster than Grunt.

What is Gulp

After dropping all these tools in the previous paragraphs you might be confused. This article will focus on getting you started with Gulp. But what is Gulp exactly?

Gulp is a task runner, it’s purpose is to perform repetitive tasks for you. When you are developing a website some things you might want to automate are:

  • Compiling css
  • Concatenate javascript files into a single file
  • Refresh your browser
  • Minify your css and javascript files

This would be a very basic setup. Some more advanced task include:

  • Running jshint
  • Generating an icon font
  • Using a cachebuster
  • Generating spritesheets

And many, many more. The way Gulp does all these things is through plugins. This makes Gulp a very small and lightweight utility that can be expanded with plugins so it does whatever you want. At this time there’s about 1200 plugins available for gulp.

When should I learn Gulp

You should learn Gulp whenever you feel like you are ready for it. When you’re starting out as a front-end developer you will have to learn so many things at once I don’t think there’s much use in immediately jumping in to use Sass, Gulp and all the other great tools that are available. If you feel like you want to learn Sass (or Less) as soon as you start learning css you don’t have to learn Gulp as well. You could manually compile your css files as you go. Or you could use a graphical tool like Codekit for the time being. Like I said, there’s no need to rush in and confuse yourself.

What about Grunt?

For those who payed attention, I mentioned Grunt at the start of this article. I don’t use Grunt for a very simple reason, I don’t like the syntax. And also, Gulp is supposed to be faster so that’s nice. I feel like it’s important to mention this because if you choose to use a tool like Gulp or Grunt you have to feel comfortable. A tool should help you get your job done better; using a tool shouldn’t be a goal in itself.

That said, Grunt fulfills the same purpose as Gulp, which is running automated tasks. The way they do it is completely different though. Grunt uses a configuration file for it’s tasks and then it runs all of the tasks in sequence. So it might take a Sass file and turn it into compiled css. After that it takes a css file and minifies it. Gulp uses javascript and streams. This means that you would take a Sass file and Gulp turns it into a so called stream. This stream then gets passed on an plugins modify it. You could compare this with an assembly line, you have some input, it get’s modified n times and then at the end you get the output. In Gulp’s case the output is a compiled and minified css file. Now, let’s dive in and create our first gulpfile.js!

Creating a gulpfile

The gulpfile is your main file for running and using gulp. Let’s create your first Gulp task!

Installing gulp

I’m going to assume you’ve already installed node and npm on your machine. If not go to the node.js website and follow the instructions over there. When you’re done you can come back here to follow along.

To use gulp you need to install it on your machine globally and locally. Let’s do the global install first:

If this doesn’t work at once you might have to use the sudo prefix to execute this command.

When this is done, you have successfully installed Gulp on your machine! Now let’s do something with it.

Setting up a project

In this example we are going to use gulp for compiling sass to css. Create the following folders/files:

In your style.scss files you could write the following contents:

Allright, we have our setup complete. Let’s set up Gulp for our project.

Setting up Gulp

Let’s start by locally installing gulp for our project:

If you’re more familiar with npm and the package.json file that you can add to your project you’ll want to run the command with --save-dev appended to it. That will add gulp as a dependency for your project. This also applies to any plugins you install.

Next up, we install the sass compiler:

We’re all set to actually build our gulpfile now. Add the following code in there:

In this file we import gulp and the gulp sass module. Then we define a task, we call the task css. Inside of this task we take our style.scss file and pipe it through to the sass plugin. What happens here is that the sass plugin modifies the stream that was created when we loaded sass/style.scss. When the sass plugin is done it sends the stream on to the next pipe call. This time we call gulp.dest to save the output of our stream to the css folder.

Think of this process as an assembly line for your files. You put the raw file in on one end, apply some plugins to it in order to build your final file and then at the end you save your output to a file.

The second task we define is called watch. This is the task we’re going to start from the command line in a bit. What happens in this task is that we tell gulp to watch everything we have in our sass folder, as long as it ends in .scss. When something changes, Gulp will start the css task.

Go back to your command line and type:

Now go to your style.scss file, change something and save it (or just save it). You should see something happening in the command line now.

That’s the output I get. If you check the css folder, there should be a css file in there. You just generated that file! That’s all there is to it.

Moving forward

Now that you’ve learned to compile sass files into css files with gulp you can start doing more advanced things. Gulps powerful syntax shouldn’t make it too hard to expand on this example. Usually you just add an extra pipe to your file, call the plugin you want, repeat that a few times and then eventually you save the output file.

I hope this guide to getting started with gulp is helpful to you. If you have notes for me, questions or just want to chat you can send me a tweet @donnywals

Weekly Swift 3, Interfaces and CoreData

This is the third post I’m writing about my swift adventure and it’s been great so far. I feel like I’ve been able to learn a lot about Swift and UIKit. I did miss two days because I was extremely busy those days, so that’s a bit of a shame.

In week three I focused on learning UI stuff rather than focusing on building Arto App, I decided to do this because a better understanding of UIKit might be very important in the process of developing it. I also took a peek at CoreData which was interesting.

UIScrollView

UIScrollView 1


I used the UIScrollView this week for making a zoomable/scrollable image and a slideshow. This was useful because I got to learn that a tableview actually subclasses the scrollview. It’s also pretty easy to get started with a scrollview and it seems like an awesome way for creating good user experiences. It just feels good to use, especially because it’s so easy to implement.


UIScrollView 2

Sidescrolling menu

Many apps today use a navigation pattern where there’s a menu hidden underneath the content of a page. Using a great tutorial from raywenderlich.com, I was able to create one of these menus and again I was amazed at how flexible and natural a lot of programming in UIKit feels. I’m only scratching the surface so there’s a lot more to be explored and probably there’s many things that aren’t as easy and straightforward as what I’ve done so far.


Slide out menu

CoreData

If you need a database to store objects in, then CoreData is what you need. This week I have used CoreData to save a list of names and birth dates. CoreData uses a database model that you can query. You access the models from CoreData through an NSManagedObject. This object is obtained through the AppDelegate which seems strange but it’s just how it works.

Actually using CoreData for something simple as this was not too hard and quite easy to understand. In the CoreData example I did, I actually found that using user input is very strange actually. When a user selects a text input field a keyboard pops up, which makes sense. But when the user taps outside of the text input, essentially taking the focus away from it, you’d expect the keyboard to disappear. But it doesn’t, because you have to manually tell the keyboard to stop responding.

No more daily projects

Starting this week I will finish one thing a day anymore. I do intent to push something to github every day but it’s my goal to make more useful things that are hard to squeeze into a single day. So my intent is to make the daily Swift something I do every other day. That way I can try to make more interesting projects that are a bit more complex than the ones I’m doing right now.

This week’s repositories

As always, if you want to follow my progress you can do so on Twitter and Github.

Understanding HTML5 srcset

Every since responsive design became a thing people worried about the sizing of their images. Why would you serve an image that’s 1800px wide to a device that is only 320px wide? That’s a very sensible question to ask when you’re dealing with responsive design. If you consider that this 320px wide device might very well be a mobile device that’s using a 3g connection this question makes even more sense.

Working towards a solution

I think it was a few years back when I saw people debating the problem of responsive images. How would the syntax look? How will it be compatible with current browsers? HTML5 isn’t supposed to break backward compatibility. I’ve seen a proposal for a element come by. That looked promising. But eventually something else come along and it’s called the srcset.

How it works

The srcset is an attribute that takes a list of images that a browser can choose from. By using the srcset you are trusting the browser to make smart decisions about what image is shown. If you want to have a crop out on small screens and then a different version on larger screens you might be in for trouble. Browsers are entirely free in their interpretations of the srcset attribute. They (should) try to be sensible, but Chrome 40 caches your images, so making the viewport smaller won’t trigger a reload on the image. Why? Well, why would it. The browser assumes that a higher resolution version is ‘better’ and it won’t waste an extra URLRequest on fetching your lesser quality image.

An example of using srcset:

The list we define uses this syntax:

We could also define a pixel density:

But I want to have some control

Understandable, while this feature is somewhat of a block box, it isn’t all black magic that goes on as Chris Coyier illustrates in his blogpost: You’re just changing resolutions. The bottom line of what he illustrates is that a browser uses simple math to determine the best image for the current case. What the browser does is devide the image width by the viewport width and then checks how it matches the current pixel density.

Example from Chris’ blog:

Imagine using a browser that has a 320px viewport. The images we are offering are 320, 640 and 960 wide. The browser does the math and decides that the 320w image is the best one since we are using a 1x pixel density device.

Now imagine using a retina device in this same case. The browser will now use the 640w image. Why? Well, a retina device has a 2x pixel density. So the 320 image is too small. It needs a bigger image.

More control please!

The browser always uses the full browser width to do the math now. But what if we needed to display images at 33% of the viewport on large screens, 50% on medium screens and 100% on small screens?

This is a question I really struggled with for a bit because here’s where things get magical. But luckily we got a great mental model to work with because of Chris Coyier’s examples. So, let’s use the same html snippet we had before but we add the rules I just specified by using the sizes attribute.

I’ve used some arbitrary values for the definition of what is small, medium and large. The first line should be explained, it says that we intend to display images at 50vw on a viewport that’s 768px wide. If it’s smaller we use 100vw. We don’t need that “if it’s smaller” part on the second size because we already defined a rule for that.

Okay, so now let’s do the math again:

With this math we can see that viewports at 320px and 640px are actually pretty predictable. A viewport with 960px is a strange case. The browser will either pick the 320w image or the 640w image. I would expect the 640w image because 1.5 can be easily rounded to 2 but it’s up to the browser to implement this.

Using the srcset

I feel like it’s pretty save to go ahead and use the srcset right now. The fallback is good since it’s just a regular tag with a source attribute set on it. However, do make sure that you sort off understand how a browser might interpret your srcset. It could save you many headaches and it will make you feel more confident about using it. if you want to know more about the srcset I strongly recommend reading You’re just changing resolutions since it’s a good description of how srcset works.

Questions, comments, notes, feedback, it’s all welcome. You can find me on twitter for that.

Weekly Swift 2, getting somewhere

Time flies, it’s been two weeks since I started my daily Swift adventure and I only missed one day. Pretty impressive I’d say. The second week of the daily Swift was a very practical one. It was all about looking through Arto App and building the components I’d need to actually build this app. Building it will be a part of the daily Swift.

Layout and Constraints

A big part of creating a beautiful feed of content seems to be understanding the UITableView. More specifically, understanding UITableViewCells. These Cells are the core of what a user will see and interact with and giants like Twitter, Facebook and Instagram all implement some custom version of a UITableViewCell.

Making my own cells appeared very hard at first. I didn’t understand what would go where, and how would I make it auto-resize itself to fit the content I put into in. After digging around on the web I found a video tutorial and a blog post that explained in part how to do this. Then I started experimenting with LayoutConstraints. These Constraints are extremely powerful and surprisingly simple to write. I’ve been getting warnings every time I used them but everything looks and works fine so I’m not sure how serious these warnings are. An example:

The text above defines a Constraint in Visual Format Language (VFL) and it says that on the vertical axis(V) there should be a 10 point margin (-10-), then myObject appears and then there’s another 10 point margin (-10-). The width of myObject in this case will be the container’s width minus two times a 10 point margin.

Delegation

In order to load data from the Arto API I wanted to have an object in my application that would manage this. I decided to use delegation as a callback style for this object. The implementation of this is actually pretty simple. In the same file as the one where I defined my API class I wrote a protocol. A protocol is defined by naming it and specifying methods that should be implemented by the implementer of this protocol.

Then, whenever the object finished loading some data I call:

The fact that there’s a question mark after self.delegate  tells the compiler that there might not be a delegate. If the delegate isn’t there, everything after the question mark is ignored.

So all I needed to do to use this, is make an ArtoAPI instance in my TableViewController, implement the ArtoAPIDelegate protocol and use the data that gets passed to didReceiveData . Easy enough, right?

Bonus: A header image effect

There’s some apps that have this very nice expanding header effect when you pull down the content below it. I have recreated this effect and it actually was surprisingly easy.

Expanding header example

Putting it together

At the end of the week I’ve spent some time putting together the parts. Combining the UITableView, UITableViewCell, ArtoAPI, loading images with Haneke and more. A picture says more than a thousand words so here’s a gif that shows the end result.

Arto Feed Example

In conclusion

The second week of the daily Swift was all about working towards creating and iOS version of Arto App. I’m still trying to decide whether week three should keep pushing forward or if week three should be about learning more small things like an off-screen menu, blurring images, using shadows, implementing POST requests to push data to a server and more of that. If you can’t wait to find out, make sure to follow me on Twitter or check out my Github regularly. Thanks for taking the time to read this and if you have any tips, comments or feedback be sure to let me know.

This week’s repositories

Weekly Swift 1, warming-up

It’s been my goal to learn how to build apps for a bunch of years now. I’ve picked up some books on Objective-C, tried building some things but lost interest really quick every time. The first time I actually went through with building something was when I was graduating from college. Shortly after that Swift came out and I wanted to learn it. But, once again, with no real goal except just learning Swift I quickly lost motivation to actually do something with it.

But then something happened, I realized that motivation is fleeting. It’s not reliable, one day I could be super motivated and the next day I was too tired to care. So I set out to become more disciplined. And part of this would be learning Swift. I decided to start something called Daily Swift. The idea is to build a (sometimes very) small and simple project in Swift. I have decided to not use Storyboards / Interface Builder because I feel like most pros out there prefer not using it. The projects I build should usually be very bare bones and exactly what I’m missing in Swift resources.

A lot of resources on Swift that I have found are either too complex, or they rely on Interface Builder to work. I feel like the things I’m going to push out are a lot more simple and don’t rely on Interface Builder. If you’re like me, a developer who is struggling with these storyboards and overly complicated examples you might want to follow along. And, more importantly you might have some feedback for me or have a subject you’d like me to look into. Please let me know on Twitter.

In my first week I’ve noticed that there’s really tons of magic in Apple’s UIKit framework. They have pretty good documentation for it but sometimes I did have to really force myself to read it all. When you just glance over everything you will surely miss a very important detail and nothing will work and there will be errors all over the place. Also, the use of ? and ! is just confusing in Swift. The ? tells the compiler that something is either an instance of a class or nil. And the ! seems to promise the compiler that you know what you’re doing and the variable (or constant) you’re using is not nil. When I have a better mental model of this I will write about it.

Also, I’m amazed with how much you can learn about Swift in just a single week. I’ve learned how to use Alerts and Actionsheets. I learned about TableViews, TabBars and NavigationControllers. And more interesting, I learned how to add images from an online resource to a TableView without blocking the main thread. (Blocking the main thread by just grabbing the images would make for very choppy scrolling.) And even more interestingly I learned how to load images with HanekeSwift thanks to a tip from @mwildeboer.

My goal for now is to be able to build a Swift version of Arto App. I built this app as an assignment during my minor and I’ve always imagined it as an iOS app. All the JSON APIs are there already so I’ll be using them as input for some examples and eventually I will bundle them together into a project that would be the iOS version for Arto.

Thanks for reading and if you want to follow my journey you can do so on Twitter and Github.

Avoid thinking in pixels

When writing CSS for websites it’s easy to use pixels for everything. Just measure up everything in the design you were given, fill out the numbers and you’re done. You’ve built a beautiful pixel perfect website. Until somebody comes along with a mobile phone. Or their 13″ laptop. Or maybe somebody is using a fancy 27″ iMac screen. The retina version I mean. Then everything looks weird. Maybe the design doesn’t quite fit, causing a vertical scroll. Or maybe the design is an old fashioned 960px grid site. That would certainly create huge amounts of whitespace. Oh and then there was that retina display. Everything looks a bit blurry there.

The point I’m trying to argue here is that pixels are old fashioned. Technically a pixel is a single RGB light that can light up together with many other lights to create an image on the screen. So when you imagine a retina display the pixels are actually smaller. So 1px on a normal screen is four(!) times larger than one on a retina display. I’ve argued with designers over this. A lot. They view a pixel as this absolute unit of design. Double the pixel density, you double the size of your design. And then you make your design. Font size 16px because that looks great. Except.. you doubled the size of your entire design. So the font sizes should double as well. And you should zoom out twice, because that’s how everything will look on your user’s screen. Probably. Because you have no clue about the actual pixel density. So, how in the hell are you supposed to solve this?

Well, the solution is simple and extremely complicated at the same time. Drop pixels. Just try to not think in terms of something being 300px wide. Think of it as 25% of the screen width. And then when you resize your browser and the layout becomes cramped, come up with a new percentage. Maybe something like 50%. And then when the screen is even smaller you might want to scale up to 100% width, allowing all columns to line up vertically so a user with a small screen can scroll down to view content. This obviously poses a few usability problems that I’ll not go in to right now. Just make sure that content can be navigated properly with a good menu for example. Okay, I’m drifting off. Let’s get back to this dropping pixels thing.

When you start defining widths as percentages for your layout you suddenly are extremely flexible. Maybe even a little responsive! Or fluid.. Or both. When you combine these percentages with good breakpoints (base these on your content, not assumptions about devices. Your assumptions are probably wrong.) you get a good responsive layout.

Another nice practice is to start working with (r)ems. The em is a unit relative to the font-size of the containing element. So if you have a section, and you give it a width and height of 10em you essentially give this element a size of 160x160px. This assumes that your user didn’t change their browser defaults. Now imagine that you have a list of four items, one should be highlighted. If you’ve defined the styling for your item in ems, you could highlight one by simply increasing it’s font size.

One last thing to mention is how you would go about converting that pixel design you were given to css without pixels. Well, you could start by calculating everything in percentages by taking the design width and the width of the component your styling. Divide the component width by the design width, multiply by 100 and there’s the percentage width. To get a size in em divide a size by the font-size (960px /16 = 60em).

This might all seem (over)complicated. And honestly, it sometimes is. And when you nest a few levels and then change the font-size everything gets even more complicated. But I feel like it’s all worth it. As soon as you start viewing your content on different devices and see how easy everything just flows into the correct places with almost no extra code, you feel like you’re totally on top of the world. Oh and you get bonuspoints for doing that mobile first. Adding things, making them larger and displaying more content is always easier than making things smaller, hiding things (hiding rarely is a good idea) and complicating interactions.

So, yeah, my two cents on a design topic. Something I’ll probably be writing more about in the future since my new job requires me to write a whole lot of front-end code.

Sharing cookies between subdomains

A while ago I wrote about sharing cookies on an old Tumblr blog of mine. I figured it contains some valuable information so I migrated the post here. The reason I wrote it was that I was working on a pitch that would take a user through a series of puzzles. Each puzzle would enable the user to see the next website(subdomain) and I decided I’d save the progress of the user in a cookie.

Normally you’d define a cookie for a domain like www.example.com. When the browser tries to read this cookie, the current domain has to be www.example.com. So sub.example.com wouldn’t work and the cookie won’t be read. There is, however, a way to get around this security limitation and it’s quite easy.

If you only specify .example.com(note the period before example.com) as the host for your cookie, it will be accessible for every subdomain from this host. So both www.example.com and sub.example.com can use this cookie.

An example in code (using the jquery cookie plugin):

Well, hope it’s helpful to some of you out there.

Using Angular UI Bootstrap modals

While working on a personal project I figured I’d use Bootstrap because then I wouldn’t have to worry about styling. All was very well and using Angular.js together with Twitter Bootstrap totally made my day. But then I needed to show a modal dialog. I know how to do this but I stumbled upon the Angular UI directives for Bootstrap this seemed great. I mean, that’s just awesome. Using the power of Angular’s directives should get these modals up and running super fast. Or so I thought..

After skimming the docs and looking at the modal example I figured I’d give it a go. I set up my templates and wrote some code. Clicked on my button and then.. nothing. Just some error message.. My code looked like this, and from the docs I understood that this would be fine.

This was just like the docs told me to do it and should’ve worked just fine. But it didn’t, my code wouldn’t find the window and backdrop templates. So I added the template folder from angular-ui to my project but that led to another error telling me my template needed one root. And one root only. This bugged me, I did the same things with my template as the examples did and they worked fine. So then I turned to some more searching online an I found this Github issue. This person was having the same issues I had and the solution was simple. He made a ‘beginners mistake’ because he forgot to list ui.bootstrap.tpls as dependency for the module that was creating the modal window. After I added this dependency everything was working just fine. So, to everybody getting an error about their templateRoot when trying to use the modals from angular ui’s bootstrap directives. Make sure you added ui.bootstrap.tpls.

My final code for the controller ended up like this:

Creating a multi step form with Angular.js

Before we start, you might want to check out this example of the form in action.

While I was working with Angular.js to create a nice little recipe / cookbook site for myself, I was creating a form that required me to split it up into multiple parts or steps. I found this surprisingly easy to do actually but I can imagine that not everybody will have the same experience I did. In this short post I will provide you with a good starting point for your html and your javascript.

I’ll be using the power of Angular.js directives to hide and show parts of the form. Well, let’s dive in then!

First of all, we’ll set up a form. It could look a little like this. I’m using bootstrap to style the form in this example. You can just ignore the classes I’ve used.

So, that’s not very bizarre right? It’s a regular Angular.js style form with a bunch of fieldsets. The magic happens with the ng-show directives that are set on the fieldsets. These directive will make sure that we will only show a certain fieldset if the step property of our controller is equal to a certain number.

Let’s tie this up with some Javascript.

If we were to test this out in an actual app we would have a pretty neat form that spans multiple steps. The model data is preserved for each because we’re just showing and hiding different parts of a single form!

Source on github